Search code examples
pythonwinapipywin32pywinautowin32gui

Posting a WM_KEYDOWN message without the following WM_CHAR message for Automating Ctrl+A


I'm trying to send a Ctrl+A message to a certain application using Python with the win32api module.

Pressing Ctrl+A and checking the messages using Spy++, this is the result:

image

The WM_CHAR message after WM_KEYDOWN for A has ASCII code 1, which is "Start of heading (SOH)".

When I send the same messages with this code:

win32gui.PostMessage(self.hwnd, win32con.WM_KEYDOWN, 0x11,0x1D0001)#VK_CONTROL
time.sleep(0.1)
win32gui.PostMessage(self.hwnd, win32con.WM_KEYDOWN, 0x41,0x1E0001)"A"
time.sleep(0.1)
win32gui.PostMessage(self.hwnd, win32con.WM_KEYUP, 0x11,0xC01D0001)
time.sleep(0.1)
win32gui.PostMessage(self.hwnd, win32con.WM_KEYUP, 0x41,0xC01E0001)

The result looks like this instead:

image

So, the WM_CHAR message after WM_KEYDOWN for A has ASCII code 97, unlike when doing it with the keyboard, so the code does not perform a "select all" in the application.

How do I determine the character code of the WM_CHAR message after sending WM_KEYDOWN?


Solution

  • As Jonathan mentioned in the article, You can't simulate keyboard input with PostMessage.

    You can try to use pykeyboard in python to implement the function of simulating keyboard input.

    k = PyKeyboard()
    
    k.press_key(k.control_key)
    
    k.tap_key('a')
    
    k.release_key(k.control_key)