I am handling the key down event on one of my controls. If the key pressed is an actual input (alphabetic, numeric, or symbol of some kind) I want to append it to a string I have. If it is a control character (enter, escape, etc..) I don't want to do anything.
Is there a quick and easy way to determine if the key code is a printable character or a control character?
Currently I am doing
if (e.KeyCode == Keys.Enter)
{
e.Handled = false;
return;
}
But I know there are probably a few more keys I don't care about that do something important in the system handler, so I don't want to handle them.
Keycode 13 is the Enter key.
keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event. event. charCode: Returns the Unicode value of a character key pressed during a keypress event.
Definition and Usage. Note: The keyCode property is deprecated. Use the key property instead.
Assuming you only have the KeyCode
, you can trying P/Invoking into the MapVirtualKey function. I'm not sure if this will work for all cultures.
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int MapVirtualKey(int uCode, int uMapType);
public static bool RepresentsPrintableChar(this Keys key)
{
return !char.IsControl((char)MapVirtualKey((int)key, 2));
}
Console.WriteLine(Keys.Shift.RepresentsPrintableChar());
Console.WriteLine(Keys.Enter.RepresentsPrintableChar());
Console.WriteLine(Keys.Divide.RepresentsPrintableChar());
Console.WriteLine(Keys.A.RepresentsPrintableChar());
Output:
false
false
true
true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With