my wpf application handles keyboard presses , # , * character voip phone.
i have bug though international keyboards, , in particular british english keyboard. listen 3 key , if shift key modifier down fire off event stuff. on british keyboard '£' character. found uk english keyboard has dedicated key '#'. listen particular key, doesn't solve case english shift-3 , countless other keyboards put somewhere else.
long story short, how listen particular character key press, whether it's key combo or single key , react it?
the function below, getcharfromkey(key key) trick.
it uses series of win32 calls decode key pressed.
this old post describes in bit more detail.
public enum maptype : uint { mapvk_vk_to_vsc = 0x0, mapvk_vsc_to_vk = 0x1, mapvk_vk_to_char = 0x2, mapvk_vsc_to_vk_ex = 0x3, } [dllimport("user32.dll")] public static extern int tounicode( uint wvirtkey, uint wscancode, byte[] lpkeystate, [out, marshalas(unmanagedtype.lpwstr, sizeparamindex = 4)] stringbuilder pwszbuff, int cchbuff, uint wflags); [dllimport("user32.dll")] public static extern bool getkeyboardstate(byte[] lpkeystate); [dllimport("user32.dll")] public static extern uint mapvirtualkey(uint ucode, maptype umaptype); public static char getcharfromkey(key key) { char ch = ' '; int virtualkey = keyinterop.virtualkeyfromkey(key); byte[] keyboardstate = new byte[256]; getkeyboardstate(keyboardstate); uint scancode = mapvirtualkey((uint)virtualkey, maptype.mapvk_vk_to_vsc); stringbuilder stringbuilder = new stringbuilder(2); int result = tounicode((uint)virtualkey, scancode, keyboardstate, stringbuilder, stringbuilder.capacity, 0); switch (result) { case -1: break; case 0: break; case 1: { ch = stringbuilder[0]; break; } default: { ch = stringbuilder[0]; break; } } return ch; }
Comments
Post a Comment