C#通过按键结束图像移动
C# End image movement by pressing key
我是 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
。
我有一个带有 Picture Box 的表格,在 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
,此后位置将不会更改。
我是 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
。
我有一个带有 Picture Box 的表格,在 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
,此后位置将不会更改。