在C# Form中监听键盘输入事件本身是很简单的,但是如果是想监听键盘上的上下左右这四个方向键,实现起来有所不同。下面我就以一个Demo简单陈述一下实现过程。
一、为了让界面能够监听键盘事件,必须实现以下代码:
1 public Form1() 2 { 3 InitializeComponent(); 4 this.KeyPreview = true;//让界面能够捕捉到键盘事件 5 this.Cursor.Dispose();//在主界面中禁用鼠标 6 }
line5:让鼠标移到form上时消失。(ps:这个demo本意是我想用来做一个类似于劲舞团的小游戏用的,所以进行了改动)
二、C# Form中默认是不监听方向键事件的,所以为了允许实现监听,需要重写方法:ProcessDialogKey,代码如下:
1 /// <summary> 2 /// 重写ProcessDialogKey,来允许监听方向键 3 /// </summary> 4 /// <param name="keycode"></param> 5 /// <returns></returns> 6 protected override bool ProcessDialogKey(Keys keycode) 7 { 8 switch (keycode) 9 { 10 case Keys.Left: 11 case Keys.Up: 12 case Keys.Right: 13 case Keys.Down: 14 return false; 15 } 16 return true; 17 }
当键盘的输入为上下左右的时候,返回false,这样就可以允许KeyDown跟KeyUp方法对方向键的监听。
三、在KeyUp跟KeyDown中进行具体实现。代码如下:
1 /// <summary> 2 /// 监听方向键的KeyDown事件 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void Form1_KeyDown(object sender, KeyEventArgs e) 7 { 8 switch (e.KeyCode) 9 { 10 case Keys.Left: 11 buttonLeft.BackgroundImage = Resources.left; 12 break; 13 case Keys.Up: 14 buttonUP.BackgroundImage = Resources.up; 15 break; 16 case Keys.Right: 17 buttonRight.BackgroundImage = Resources.right; 18 break; 19 case Keys.Down: 20 buttonDown.BackgroundImage = Resources.down; 21 break; 22 } 23 } 24 /// <summary> 25 /// 监听方向键的KeyUp事件 26 /// </summary> 27 /// <param name="sender"></param> 28 /// <param name="e"></param> 29 private void Form1_KeyUp(object sender, KeyEventArgs e) 30 { 31 switch (e.KeyCode) 32 { 33 case Keys.Left: 34 buttonLeft.BackgroundImage = Resources.left_dark; 35 break; 36 case Keys.Up: 37 buttonUP.BackgroundImage = Resources.up_dark; 38 break; 39 case Keys.Right: 40 buttonRight.BackgroundImage = Resources.right_dark; 41 break; 42 case Keys.Down: 43 buttonDown.BackgroundImage = Resources.down_dark; 44 break; 45 } 46 }
监听事件中实现的功能很简单,就是对表示方向的四个按钮进行背景图片的转换,以来表示当前所按的具体的哪一个方向键。具体效果如下:
界面比较简单,虽然是丑了点。^.^,仅当演示demo所用。
以上!