我重写ProcessCmdKey,当我得到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应在OnKeyDown或OnKeyUp中处理,具体取决于您的情况.
从MSDN开始:
Key events occur in the following
order:
- 07002
- 07003
- 07004
The KeyPress event is not raised by
noncharacter keys; however,the
noncharacter keys do raise the KeyDown
and KeyUp events.
例
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,e.g. char.IsSymbol } }