Convert character to virtual key code

久未见 提交于 2019-12-01 08:58:40

Sending WM_KEYDOWN/UP is troublesome. The application itself already translates the WM_KEYDOWN message into WM_CHAR, using the state of the modifier keys (Shift, Alt, Ctrl) and the keyboard layout. Neither of which you can control, you'll get the wrong character, randomly.

Just send WM_CHAR messages, set the wparam to the character code. No need to worry about lparam, few apps ever use it.

VkKeyScanEx anyone? According to MSDN it:

"Translates a character to the corresponding virtual-key code and shift state."

(You could possibly also use VkKeyScan but beware that it has been superseded by VkKeyScanEx.)

It looks like it takes the ASCII character and turns it into hex. For example, 'A' in hex is 41. According to your chart, A is 0x41, which is right (the 0x detonates hex).

Generally speaking, instead of sending WM_KEYDOWN, WM_CHAR and WM_KEYUP messages directly, you should use SendInput (preferred) or possibly keybd_event (deprecated).

You can use Input Simulator library which provides a high level api for simulating key presses and handles all the low level stuff.

System.Windows.Forms.SendKeys is a WinForms class with static methods for simulating keyboard input on the active window.

The catch is that .NET has no way of focusing windows in another application (the SendKeys docs talk about how to get around that).

The general solution is to use the SendMessage WinAPI function. This link describes SendMessage's signature and provides a sample import.

Oh and, to map VK codes you should use MapVirtualKey - its best to assume the mapping is arbitrary and not logical.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!