[python-win32] Using SendMessage to send an accelerator key combination

Daniel F nanotube at gmail.com
Tue Apr 12 19:43:11 CEST 2005

>  I've read the thread on this list titled "Help on using
> win32api.SendMessage to send keystrokes," some of the PyWin32 documentation,
> and some of the MSDN docs on SendMessage, but am still unclear about how to
> construct a message to send simple accelerator key combinations to a window,
> such as the following:
>  Could anyone point me to the right documentation to understand what
> characters to include in the "message" argument of the
> win32gui.SendMessage() call to send either of these two accelerator key
> combinations?  I just need a good example to get me going.

sendmessage itself has no way to specify that you are sending a key
combination, it can only send single keys. so... the obvious thing to
do would be to do the following:

win32api.PostMessage(HWND, win32con.WM_KEYDOWN, win32con.VK_CONTROL, lParamBits)
win32api.PostMessage(HWND, win32con.WM_KEYDOWN, 0x53, lParamBits)
win32api.PostMessage(HWND, win32con.WM_KEYUP, 0x53, lParamBits)
win32api.PostMessage(HWND, win32con.WM_KEYUP, win32con.VK_CONTROL, lParamBits)

where the lparambits are the appropriate bits, as per the win api
documentation for WM_KEYDOWN (check msdn)

in other words: press control, press S (keycode 0x41), release S,
release control.
however, it seems that some apps (at least notepad - my test case) do
not treat that as expected. so that sequence merely produces an 's' in
the notepad window, rather than bring up the save box. but if you hold
control manually, while sending the s key through your code, that
brings up the save as box. So it appears that notepad checks the key
state directly, using either GetKeyState or GetKeyboardState for the

so in order to fool notepad, and probably other apps as well (havent
tested on anything else... it may work for your specific case,
depending on what app you want to use this with), you would have to
fool getkey[board]state.

So, you would have to use SetKeyboardState api and set the values for
control, or shift, or whatever you want to use, to the down state,
THEN send it the key through sendmessage, and THEN reset the keyboard
state to normal.

unfortunately, it appears that pywin32 does not wrap the
getkeyboardstate/setkeyboardstate api, (although v204 was just
released, and i am running 203, so maybe this was added in v204?). so
you could get stuck using ctypes, which is generally a somewhat less
pleasant experience than using pywin32.

now, note that i myself am not a python guru by far (just started
playing with python, and the windows api, just about at the start of
that win32api.SendMessage thread you referenced), so i may be missing
stuff, or be completely wrong, but this is my understanding, and I
hope it helps. :)


More information about the Python-win32 mailing list