Question

Here's my code to send the keys from the string "Hello world" . I have an instance of notepad open, proof is that the string "found" is printed, but nothing appears on my notepad.

Any ideas ?

import win32con
import win32api
import win32gui

def enumHandler(hwnd, lParam):
    if win32gui.IsWindowVisible(hwnd):
        if 'Notepad' in win32gui.GetWindowText(hwnd):
            print 'found'
            for c in "Hello World\n":
                win32api.PostMessage(
                                    hwnd,
                                    win32con.WM_CHAR,
                                    ord(c),
                                    0)

win32gui.EnumWindows(enumHandler, None)
Was it helpful?

Solution

The problem is that you are sending the messages to the main Notepad window. That's the top-level window that has the caption bar. The messages will be processed by the EDIT control that is a child of the top level window. You can only make this work by sending the messages there.

However, I'm sure that your real problem is different from faking keyboard input to the Notepad program. And your real problem is most likely best solved a different way. Windows provides UIAutomation for the purpose of automating applications. That is most likely the right solution to your actual problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top