How can I convert backslash key (\'\\\') to key code?
On my keyboard backslash code is 220, but the method below
(int)\'\\\\\'
ret
Or you could keep it simple and cast it.
(Keys)keyToConvert
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.
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;
}
There is not a function that I know of that will map a character to a virtual key code. However, you can use the following table to start building such a mapping.
http://msdn.microsoft.com/en-us/library/dd375731(v=VS.85).aspx.
Note that you will need to know the keyboard, looking at the key you mention '\' this is the VK_OEM_5 virtual key which for US keyboards is '\' if not shifted and '|' if shifted, so your function will need to know the keyboard being used as well.
Of course if you want to map from a virtual key code to a character you can use interop to call the MapVirtualKeyEx function.
Update Based on your comment this would give you what you want.
[DllImport("user32.dll")]
static extern int MapVirtualKey(int uCode, uint uMapType);
const uint MAPVK_VK_TO_CHAR = 0x02;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
int key = MapVirtualKey((int)e.KeyCode, MAPVK_VK_TO_CHAR);
if (key == (int)'\\')
{
}
}