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

3 投票
1 回答
3038 浏览
提问于 2025-04-16 14:02

我在想,怎么才能用wxPython和win32api一起写个简单的脚本,让一个特定标题的窗口(如果它还没被激活的话)变得活跃,并且输出一些文本(模拟按键)。这个功能在游戏中可以用来设置快捷键。我查过wxPython的RegisterHotKey(),但作为一个业余的Python程序员,我还是不太明白。
这个脚本的基本结构大概是:

  1. 定义一个快捷键(比如win+F_)
  2. 监听这个快捷键的按下
  3. 检查一下想要的窗口(标题)是否已经激活,如果没有就激活它
  4. 模拟输入一些文本

我知道有更简单的方法可以做到这一点(比如AutoHotkey),但我更喜欢用自己写的代码,而且我对Python也很感兴趣。
谢谢!

顺便说一下,我是在Windows 7 AMD64上使用Python 2.7,虽然我觉得解释器的版本、平台或架构在这里没什么太大区别。

1 个回答

4

你是在说激活你用wx创建的窗口,还是像记事本这样的其他应用程序呢?如果是wx的窗口,那就简单多了。你只需要用Raise()这个方法就能把你需要的窗口调到最前面。你可能还会用到PubSub或者PostEvent来通知子窗口需要被激活。

如果你是在说记事本,那事情就复杂多了。这是我根据网上的一些资料和PyWin32邮件列表的信息,做出的一个不太优雅的解决办法:

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。这样会更可靠。

撰写回答