Python 如何使用 SendKeys 将模拟键盘敲击发送到活动窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4636887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:39:51  来源:igfitidea点击:

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

pythonwinapiwindows-7sendkeys

提问by pat

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.

我是 Python 新手,正在尝试将按键组合发送到我在 Windows 7 下打开的应用程序。虽然当我出于测试目的调用 Notepad.exe 时,我的脚本可以完美运行,但它不适用于我正在尝试的实际应用程序使用。

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?

出于某种原因,应用程序不会响应脚本而关闭。当我在键盘上按下“Alt + F4”时,它会按预期关闭。关于这里可能发生什么的任何想法?

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

欢迎任何帮助!请记住,我是 Python 新手;-)

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

PS:我已经通过包含以下代码片段验证了该应用程序在活动窗口中运行:

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

回答by pat

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.

感谢所有花时间回复的人。

回答by Lucas Ribeiro Alves

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

我知道这是 6 年前问过的,但有人可能遇到同样的问题,所以这里有一个可能的解决方案:

shell.AppActivate('Put_The_Name_Here')

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!

希望这可以帮助某人!