4

I'm trying to press a key in another process from a Python program. I've tried the win32 api, but somehow this code does nothing:

import win32gui
import win32con
import win32api

hwnd = win32gui.FindWindow("notepad", "prueba.txt: Bloc de notas")

if(hwnd != 0):

    win32api.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    win32api.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)

    while(True):

        win32api.SendMessage(
            hwnd,
            win32con.WM_CHAR,
            ord('x'),
            0)
else:
    print("The window is closed")

Of course I want to do this to an inactive window. Any solution or alternatives?

Thanks

2 Answers2

1

Use (but add error checking)

hwndMain = win32gui.FindWindow("notepad", "prueba.txt: Bloc de notas")
hwndEdit = win32gui.FindWindowEx( hwndMain, 0, "Edit", 0 )
win32api.PostMessage( hwndEdit,win32con.WM_CHAR, ord('x'), 0)

you should add some "sleep" calls if you want to loop posting message :-)

manuell
  • 7,528
  • 5
  • 31
  • 58
  • Thank you guys. What about emulators and games that do not aceppt postmessage? I've tried keybd_event but it's really slow because you must wait like 0.1 seconds. –  Feb 23 '14 at 18:15
  • I you can't or don't want to use PostMessage WM_CHAR (or WM_KEYDOWN), then you are left with SendInput. I m not aware of any "wait" needed by SendInput; See http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310.aspx If the code posted worked for you, you should accept the answer. You may be able to upvote answers when you'll have more reps. – manuell Feb 23 '14 at 19:22
  • I think SendInput doesn't work in emulators and games :( –  Feb 24 '14 at 20:32
  • Anyway, if my code helped you to fill Notepad with 'x', you may accept the answer :-) If `keybd_event` works, `SendInput` should work as well. And if `SendInput` doesn't work, I am not aware of another solution. – manuell Feb 25 '14 at 12:19
0

The target window is wrong. Notepad has more than 1 window: it has a frame window with child edit control. To make your code work you should find a child of frame (= hwnd in your code) that is an edit control and send WM_CHARs to it.

KonstantinL
  • 667
  • 1
  • 8
  • 20