Check for Letter / Digit / Special Symbol Keys

I override ProcessCmdKey , and when I get the Keys argument, I want to check if this Keys letter or number or a special character.

I have this snippet

  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); } 

Everything works for letters and numbers. but when I press F1-F12, it converts them to letters.

Can anyone know a better way to solve this problem?

+7
c # key
source share
6 answers

Instead, change the OnKeyPress form OnKeyPress . KeyPressEventArgs provides a KeyChar property that allows the use of static methods on char .

As mentioned in the comments of Cody Gray, this method only works when keystrokes containing symbolic information are pressed. Other key touches, such as F1-F12, should be handled in OnKeyDown or OnKeyUp , depending on your situation.

From MSDN :

Key events occur in the following order:

KeyPress event does not raise uncharacteristic keys ; However, uncharacteristic keys do raise KeyDown and KeyUp events.

Example

 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 } } 
+11
source share

Try

 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); 
+3
source share

Try using keyData.KeyCode and possibly even testing within a range instead of using Char.IsLetterOrDigit. eg.

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

you need either a giant switch / case statement or range checking. It may be easier for you to verify the keys that you want to exclude, whichever is the smaller. Look at this for all possible values. http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx

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

or

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

I tried the following code, but for some reason the char.IsLetter () method recognizes the following keys as letters

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

This method does not seem to be a complete proof of what it considers to be a letter.

 if(char.IsLetter((char)e.Key) || char.IsDigit((char)e.Key)) 
-one
source share

All Articles