C#按键结束图像移动



我是C#的新手,想知道如何制作它,这样一旦用户按下回车键,图像的当前位置就会变成它的固定位置。我想最好的方法是使用while循环。非常感谢您的帮助。以下是我移动图像的代码:

private void pictureBox1_KeyDown(object sender, KeyEventArgs e)
{
int x = pictureBox1.Location.X;
int y = pictureBox1.Location.Y;
{
if (e.KeyCode == Keys.Right) x += 50;
else if (e.KeyCode == Keys.Left) x -= 50;
else if (e.KeyCode == Keys.Up) y -= 50;
else if (e.KeyCode == Keys.Down) y += 50;
pictureBox1.Location = new Point(x, y); 
}
}

在这个解决方案中,我使用了一个全局bool对象,并在按下回车键后将标志更改为true。我有一个带有图片框的表单,在form_KeyDown活动中,我放置了您的代码,并进行了少量更改。

bool bIsEnterKeyPressed = false;
private void frmSampleJson_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
bIsEnterKeyPressed = true;
}
if (!bIsEnterKeyPressed)
{
int x = pictureBox1.Location.X;
int y = pictureBox1.Location.Y;
{
if (e.KeyCode == Keys.Right) x += 50;
else if (e.KeyCode == Keys.Left) x -= 50;
else if (e.KeyCode == Keys.Up) y -= 50;
else if (e.KeyCode == Keys.Down) y += 50;
pictureBox1.Location = new Point(x, y);
}
}
}

按下回车键后,bIsEnterKeyPressed将变为true,此后位置将不会更改。