某些键,如 Tab、Return、Esc 和箭头键,由控件自动处理。为使这些键引发 KeyDown 事件,必须在窗体上的每个控件中重写 IsInputKey 方法。用于重写 IsInputKey 的代码需要确定是否按下了某个特殊键,并且需要返回一个 true 值。
1
class
MyButton :System.Windows.Forms.Button
2
{
3
protected override bool IsInputKey(System.Windows.Forms.Keys keyData)
4
{
5
if (keyData == System.Windows.Forms.Keys.Left ||
6
keyData == System.Windows.Forms.Keys.Right)
7
return true;
8
return base.IsInputKey(keyData);
9
}
10
}
class
MyButton :System.Windows.Forms.Button2
{3
protected override bool IsInputKey(System.Windows.Forms.Keys keyData)4
{5
if (keyData == System.Windows.Forms.Keys.Left ||6
keyData == System.Windows.Forms.Keys.Right)7
return true;8
return base.IsInputKey(keyData);9
}10
}
重写之后就可以让Button控件KeyDown事件中箭头键响应了。
1
private
void
button1_KeyDown(
object
sender, KeyEventArgs e)
2
{
3
if(e.KeyCode == Keys.Left)
4
{
5
if (button1.Location.X >=2)
6
{
7
button1.Location = new Point(button1.Location.X - 2, button1.Location.Y) ;
8
}
9
}
10
if (e.KeyCode == Keys.Right)
11
{
12
if (button1.Location.X <= 500)
13
{
14
button1.Location = new Point(button1.Location.X + 2, button1.Location.Y);
15
}
16
}
17
}
private
void
button1_KeyDown(
object
sender, KeyEventArgs e)2
{3
if(e.KeyCode == Keys.Left)4
{5
if (button1.Location.X >=2)6
{7
button1.Location = new Point(button1.Location.X - 2, button1.Location.Y) ;8
}9
}10
if (e.KeyCode == Keys.Right)11
{12
if (button1.Location.X <= 500)13
{14
button1.Location = new Point(button1.Location.X + 2, button1.Location.Y);15
}16
}17
}
本文介绍如何通过重写IsInputKey方法使C#中的Button控件响应特定键盘输入,例如左右箭头键,并展示了如何利用KeyDown事件来实现按钮位置的调整。

1121

被折叠的 条评论
为什么被折叠?



