在C# WinForm中监听键盘输入事件本身是很简单的,但是如果是想监听键盘上的上下左右这四个方向键,实现起来有所不同。下面我就以一个Demo简单陈述一下实现过程。
一、为了让界面能够监听键盘事件,必须实现以下代码:
public Form1()
{
InitializeComponent();
this.KeyPreview = true;//让界面能够捕捉到键盘事件
}
二、C# Form中默认是不监听方向键事件的,所以为了允许实现监听,需要重写方法:ProcessDialogKey,代码如下:
/// <summary>
/// 重写ProcessDialogKey,来允许监听方向键
/// </summary>
/// <param name="keycode"></param>
/// <returns></returns>
protected override bool ProcessDialogKey(Keys keycode)
{
switch (keycode)
{
case Keys.Left:
case Keys.Up:
case Keys.Right:
case Keys.Down:
return false;
}
return true;
}
当键盘的输入为上下左右的时候,返回false,这样就可以允许KeyDown跟KeyUp方法对方向键的监听。
三、在KeyUp跟KeyDown中进行具体实现。代码如下:
/// <summary>
/// 监听方向键的KeyDown事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
buttonLeft.BackgroundImage = Resources.left;
break;
case Keys.Up:
buttonUP.BackgroundImage = Resources.up;
break;
case Keys.Right:
buttonRight.BackgroundImage = Resources.right;
break;
case Keys.Down:
buttonDown.BackgroundImage = Resources.down;
break;
}
}
/// <summary>
/// 监听方向键的KeyUp事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
buttonLeft.BackgroundImage = Resources.left_dark;
break;
case Keys.Up:
buttonUP.BackgroundImage = Resources.up_dark;
break;
case Keys.Right:
buttonRight.BackgroundImage = Resources.right_dark;
break;
case Keys.Down:
buttonDown.BackgroundImage = Resources.down_dark;
break;
}
}
监听事件中实现的功能很简单,就是对表示方向的四个按钮进行背景图片的转换,以来表示当前所按的具体的哪一个方向键。