I override ProcessCmdKey
and when I get Keys
argument, I want to check if this Keys
is Letter or Digit or Special Symbol.
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 digits. but when I press F1-F12 it converts them to letters.
Maybe someone knows better way to solve this task?
Try using
keyData.KeyCode
and maybe even testing within a range instead of using the Char.IsLetterOrDigit. e.g.Try
I have tried the following code but for some reason char.IsLetter() method is recognising the following keys as Letters???
F1, F8, F9, F11, F12, RightShift, LeftShift, RightAlt, RightCtrl, LeftCtrl, LeftWin, RightWin, NumLock.
This method doesn't seem to be that full proof regarding what it thinks is a letter.
you need either a giant switch/case statement or check for ranges. You may find it easier to check for the keys you want to exclude, depending on which there is fewer of. Look at this for all the possible values. http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx
or
Override the form's
OnKeyPress
method instead. TheKeyPressEventArgs
provides aKeyChar
property which allows you to utilize the static methods onchar
.As mentioned by Cody Gray in the comments, this method only fires on key strokes that have character information. Other key strokes such as F1-F12 should be processed in
OnKeyDown
orOnKeyUp
, depending on your situation.From MSDN:
Example