我在 C# 中移动按钮时遇到问题。我曾经想过很多次。而且我还没有弄清楚我的代码有什么问题。如果你们能找出我的错误在哪里,请帮助我。之前非常感谢。
这是我的方法,应该在按下箭头键时移动按钮。
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyValue == 39)
{
button1.Location = new Point(button1.Location.X + 1, button1.Location.Y);
}
else if (e.KeyValue == 37)
{
button1.Location = new Point(button1.Location.X - 1, button1.Location.Y);
}
}
最佳答案
问题是箭头键是一种由控件自动处理的特殊键。因此,您可以通过以下方式之一处理按箭头键:
第一种方法:
我建议您使用ProcessCmdKey
而不处理任何key
事件:
public Form1()
{
InitializeComponent();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Left)
{
pad.Location = new Point(pad.Location.X - 1, pad.Location.Y);
return true;
}
else if (keyData == Keys.Right)
{
pad.Location = new Point(pad.Location.X + 1, pad.Location.Y);
return true;
}
else if (keyData == Keys.Up)
{
return true;
}
else if (keyData == Keys.Down)
{
return true;
}
else
return base.ProcessCmdKey(ref msg, keyData);
}
第二种方式:
但是如果您想使用事件来解决此问题,您可以使用 KeyUp
事件而不是 KeyDown
事件。
public Form1()
{
InitializeComponent();
this.BringToFront();
this.Focus();
this.KeyPreview = true;
this.KeyUp += new KeyEventHandler(Form1_KeyUp);
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == 39)
{
pad.Location = new Point(pad.Location.X + 1, pad.Location.Y);
}
else if (e.KeyValue == 37)
{
pad.Location = new Point(pad.Location.X - 1, pad.Location.Y);
}
}
关于c# - 以编程方式移动按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23043280/