How to send simulated keyboard strokes to the active window using SendKeys

26,320

OK ... I rebooted the system and for some reason it is working now. I am wondering if some process instance from previous programme invocations might have been lingering on the system. Anyway, I am now able to perform the manipulations as expected, even if I don't really understand what went wrong in the first place.

Thanks to everyone who took the time to repsond.

Share:
26,320
pat
Author by

pat

Updated on May 17, 2020

Comments

  • pat
    pat almost 4 years

    I am new to Python and am trying to send a combination of key strokes to an application I open under Windows 7. While my script will work flawlessly when I invoke Notepad.exe for testing purposes, it does not with the actual application I am trying to use.

    Here is my code so far:

    import win32com.client
    import time
    import SendKeys
    import os
    from ctypes import *
    
    shell = win32com.client.Dispatch("WScript.Shell")
    
    os.startfile("C:\...exe")
    
    time.sleep( 5 )
    
    shell.SendKeys('%{F4}')     # 'Alt+F4' to close the application again.
    

    For some reason, the application does not close in reaction to the script. When I hit 'Alt + F4' on my keyboard, it closes as expected. Any ideas on what might be going on here?

    Any help is welcome! Please bear in mind that I am new to Python ;-)

    PS: I have already verified that the application runs in the active window by including this code snippet:

    import win32ui
    wnd = win32ui.GetForegroundWindow()
    print wnd.GetWindowText()