检查键是否是字母/数字/特殊符号

我重写ProcessCmdKey ,当我得到Keys参数时,我想检查这些Keys是字母还是数字还是特殊符号。

我有这个片段

  protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { char key = (char)keyData; if(char.IsLetterOrDigit(key) { Console.WriteLine(key); } return base.ProcessCmdKey(ref msg, keyData); } 

一切都适用于字母和数字。 但是当我按下F1-F12时,它会将它们转换成字母。

也许有人知道更好的方法来解决这个任务?

改为覆盖表单的OnKeyPress方法。 KeyPressEventArgs提供了一个KeyChar属性,允许您在char上使用静态方法。

正如Cody Gray在评论中所提到的,这种方法只会触发具有角色信息的击键。 其他击键如F1-F12应在OnKeyDownOnKeyUp ,具体取决于您的情况。

来自MSDN :

关键事件按以下顺序发生:

  • 的KeyDown
  • 按键
  • KEYUP

非字符键不会引发KeyPress事件 ; 但是,非字符键会引发KeyDown和KeyUp事件。

 protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); if (char.IsLetter(e.KeyChar)) { // char is letter } else if (char.IsDigit(e.KeyChar)) { // char is digit } else { // char is neither letter or digit. // there are more methods you can use to determine the // type of char, eg char.IsSymbol } } 

尝试

 if( !(keyData >= Keys.F1 && keyData <= Keys.F12)) { char key = (char)keyData; if(char.IsLetterOrDigit(key)) { Console.WriteLine(key); return false; } } return base.ProcessCmdKey(ref msg, keyData); 

尝试使用keyData.KeyCode ,甚至可以在一个范围内进行测试,而不是使用Char.IsLetterOrDigit。 例如

 if (keyData.KeyCode >= Keys.D0 && keyData.KeyCode <= Keys.Z) { ... } 
 if (keyData >= Keys.F1 && keyData <= Keys.F12) { //one of the key between F1~F12 is pressed } 

你需要一个巨大的开关/案例陈述或检查范围。 您可能会发现更容易检查要排除的密钥,具体取决于哪些密钥较少。 查看所有可能的值。 http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx

 if (keyData >= Keys.A && keyData <= Keys.Z) // do something 

要么

 switch(keyData) { case Keys.Add: case Keys.Multiply: // etc. // do something break; } 

我尝试了以下代码但由于某种原因char.IsLetter()方法将以下键识别为字母???

F1,F8,F9,F11,F12,RightShift,LeftShift,RightAlt,RightCtrl,LeftCtrl,LeftWin,RightWin,NumLock。

这种方法似乎并不完全certificate它认为是一封信。

 if(char.IsLetter((char)e.Key) || char.IsDigit((char)e.Key))