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

人盡茶涼 提交于 2019-11-30 18:22:11

问题


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()

回答1:


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.




回答2:


I know this was asked 6 years ago, but someone might be with the same problem, so here is a possible solution:

shell.AppActivate('Put_The_Name_Here')

The code above will select the program, file, etc that is opened but not activated, that, maybe, is your problem.

Hope this helps someone!



来源:https://stackoverflow.com/questions/4636887/how-to-send-simulated-keyboard-strokes-to-the-active-window-using-sendkeys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!