如何使用 SendKeys 将模拟键盘敲击发送到活动窗口 [英] How to send simulated keyboard strokes to the active window using SendKeys

查看:30
本文介绍了如何使用 SendKeys 将模拟键盘敲击发送到活动窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我目前的代码:

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.

出于某种原因,应用程序没有关闭以响应脚本.当我在键盘上按下Alt + F4"时,它会按预期关闭.对这里可能发生的事情有什么想法吗?

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?

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

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

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

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

推荐答案

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

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!

这篇关于如何使用 SendKeys 将模拟键盘敲击发送到活动窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆