Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 715
pat Avatar asked Jan 25 '26 09:01

pat


1 Answers

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.

like image 143
pat Avatar answered Jan 27 '26 22:01

pat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!