winform 窗体 键盘按键 获取

来源:互联网 发布:日本mma 知乎 编辑:程序博客网 时间:2024/06/11 18:28

1) 这三个事件调用的先后顺序(MSDN)

     1. KeyDown    :在控件有焦点的情况下按下键时发生

     2. KeyPress   :在控件有焦点的情况下按下键时发生。

     3. KeyUp         :在控件有焦点的情况下释放键时发生。

2) KeyDown和KeyPress在MSDN上的解释完全一样,都是在按下键的时候发生,那区别是什么呢?

[csharp] view plain copy
  1. textBox1_KeyDown(object sender, KeyEventArgs e)  
  2. textBox1_KeyPress(object sender, KeyPressEventArgs e)  
  3. textBox1_KeyUp(object sender, KeyEventArgs e)
KeyDown和KeyUp用的是KeyEventArgs,KeyPress 用的是KeyPressEventArgs。

KeyEventArgs 提供了KeyCode,KeyData等System.Windows.Forms.Keys里定义的枚举。

KeyPressEventArgs里自只定义了个KeyChar,并且是char型的

1, KeyPress里取消输入 (A不能输入)

[csharp] view plain copy
  1. private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
  2. {  
  3.     if (e.KeyChar == 'A')  
  4.     {  
  5.         e.Handled = true;  
  6.     }  
  7. }  

2,KeyDown里取消输入 (A不能输入)

[csharp] view plain copy
  1. private void textBox1_KeyDown(object sender, KeyEventArgs e)  
  2. {  
  3.     if (e.KeyCode == Keys.A)  
  4.     {  
  5.         e.SuppressKeyPress();  
  6.     }  
  7. }  

SuppressKeyPress方法可以取消KeyPress事件,注意此时KeyUp事件也被取消了(实验得知)。


0 0