Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a character to key code?

Tags:

c#

.net

How can I convert backslash key ('\') to key code?

On my keyboard backslash code is 220, but the method below

(int)'\\'

returns me 92.

I need some generic conversion like

 int ConvertCharToKeyValue(char c)
 {
     // some code here...
 }

Any ideas?

like image 998
Murat from Daminion Software Avatar asked May 24 '10 17:05

Murat from Daminion Software


People also ask

How do I find the keycode of a character?

charCodeAt() method returns returns keycode for an character.

What are key codes?

A key code is a series of alphanumeric characters used by locksmiths to create a key. There are two kinds of key codes: blind codes and bitting codes.

What is the keycode for the spacebar?

the keyCode=49 for a space.


2 Answers

You can P/Invoke VkKeyScan() to convert a typing key code back to a virtual key. Beware that the modifier key state is important, getting "|" requires holding down the shift key on my keyboard layout. Your function signature doesn't allow for this so I just made something up:

public static Keys ConvertCharToVirtualKey(char ch) {
    short vkey = VkKeyScan(ch);
    Keys retval = (Keys)(vkey & 0xff);
    int modifiers = vkey >> 8;

    if ((modifiers & 1) != 0) retval |= Keys.Shift;
    if ((modifiers & 2) != 0) retval |= Keys.Control;
    if ((modifiers & 4) != 0) retval |= Keys.Alt;

    return retval;
}

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern short VkKeyScan(char ch);

Also beware of keyboard layouts that need to use dead keys (Alt+Gr) to generate typing keys. This kind of code is really best avoided.

like image 136
Hans Passant Avatar answered Oct 07 '22 19:10

Hans Passant


If

var char = System.Windows.Forms.Keys.OemPipe; // 220
var code = (int)char;

then

public static int ToKeyValue(this char ch)
{
    return (int)(System.Windows.Forms.Keys)ch;
}
like image 41
abatishchev Avatar answered Oct 07 '22 20:10

abatishchev