Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if KeyCode is printable character

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.

like image 250
captncraig Avatar asked Sep 03 '10 19:09

captncraig


People also ask

What is e keyCode === 13?

Keycode 13 is the Enter key.

What is the difference between keyCode and charCode?

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.

What can I use instead of E keyCode?

Definition and Usage. Note: The keyCode property is deprecated. Use the key property instead.


1 Answers

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
like image 152
Ani Avatar answered Sep 26 '22 09:09

Ani