May 30th, 2005

You can't simulate keyboard input with PostMessage

Some people attempt to simulate keyboard input to an application by posting keyboard input messages, but this is not reliable for many reasons. First of all, keyboard input is a more complicated matter than those who imprinted on the English keyboard realize. Languages with accent marks have dead keys, Far East languages have a variety of Input Method Editors, and I have no idea how complex script languages handle input. There’s more to typing a character than just pressing a key. Second, even if you manage to post the input messages into the target window’s queue, that doesn’t update the keyboard shift states. When the code behind the window calls the GetKeyState function or the GetAsyncKeyState function, it’s going to see the “real” shift state and not the fake state that your posted messages have generated.

The SendInput function was designed for injecting input into Windows. If you use that function, then at least the shift states will be reported correctly. (I can’t help you with the complex input problem, though.)

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.

Feedback