gpt4 book ai didi

python - Python 中的简单热键脚本 - 如何设置全局热键以发送文本字符串?

转载 作者:太空宇宙 更新时间:2023-11-03 15:27:03 24 4
gpt4 key购买 nike

我想知道如何将 wxPython 与 win32apis 一起使用来创建一个简单的脚本,该脚本将激活一个具有特定标题和输出文本(击键)的窗口(如果它尚未激活)。一种可能的应用是游戏中的键盘快捷键。我已经阅读了有关 wxPython RegisterHotKey() 的内容,但是-作为一名业余 Python 程序员-我不清楚。
脚本的基本结构是:

  1. 定义热键(类似于 win+F_)
  2. 注意热键击键
  3. 查看所需的窗口(标题)是否已经处于事件状态,如果不是,则激活它
  4. 模拟输入一些文字

我知道有更简单的方法来实现这一点(例如 AutoHotkey),但我觉得使用我自己编写的东西更舒服并且对 Python 感兴趣。
谢谢!

郑重声明,我在 Windows 7 AMD64 上使用 Python 2.7,但我怀疑解释器版本/平台/架构在这里有很大的不同。

最佳答案

您是在谈论激活您在 wx 或单独的应用程序(如记事本)中创建的窗口吗?如果它与 wx 一起使用,那么它是微不足道的。您只需使用 Raise() 即可将您需要的任何框架聚焦。您可能会使用 PubSub 或 PostEvent 让子框架知道它需要 Raise。

如果您谈论的是记事本,那么事情就会变得更加棘手。这是我根据从 Web 上的不同位置和 PyWin32 邮件列表获得的一些东西创建的一个丑陋的 hack:

def windowEnumerationHandler(self, hwnd, resultList):
'''
This is a handler to be passed to win32gui.EnumWindows() to generate
a list of (window handle, window text) tuples.
'''

resultList.append((hwnd, win32gui.GetWindowText(hwnd)))

def bringToFront(self, windowText):
'''
Method to look for an open window that has a title that
matches the passed in text. If found, it will proceed to
attempt to make that window the Foreground Window.
'''
secondsPassed = 0
while secondsPassed <= 5:
# sleep one second to give the window time to appear
wx.Sleep(1)

print 'bringing to front'
topWindows = []
# pass in an empty list to be filled
# somehow this call returns the list with the same variable name
win32gui.EnumWindows(self.windowEnumerationHandler, topWindows)
print len(topWindows)
# loop through windows and find the one we want
for i in topWindows:
if windowText in i[1]:
print i[1]
win32gui.ShowWindow(i[0],5)
win32gui.SetForegroundWindow(i[0])
# loop for 5-10 seconds, then break or raise
handle = win32gui.GetForegroundWindow()
if windowText in win32gui.GetWindowText(handle):
break
else:
# increment counter and loop again
secondsPassed += 1

然后我使用 SendKeys 包将文本发送到窗口(参见 http://www.rutherfurd.net/python/sendkeys/ )。如果用户打开其他任何东西,脚本就会中断或者会发生奇怪的事情。如果您打开类似 MS Office 的软件,请使用 win32com 而不是 SendKeys。这要可靠得多。

关于python - Python 中的简单热键脚本 - 如何设置全局热键以发送文本字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5365133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com