A simple Script hotkey in Python. How to set a global hotkey to send a line of text?

I was wondering how I can use wxPython with win32apis to create a simple script that activates a window (if it is not already active) with a specific title and output text (keystrokes). One possible application for this would be a keyboard shortcut in games. I read on wxPython RegisterHotKey (), but - as an amateur Python programmer - I don't understand.
The main structure of the script will be:

  • Define a hotkey (something like win + F_)
  • Watch out for the hotkey.
  • See if the desired window (name) is already activated, and activate it if it isn’t
  • Simulate text typing

I know that there are simpler methods for this (for example, AutoHotkey), but I feel more comfortable using what I wrote myself and have shown interest in Python.
Thank you

For the record, I use Python 2.7 on Windows 7 AMD64, although I doubt that the interpreter version / platform / architecture is of great importance here.

+3
source share
1 answer

Are you talking about activating a window that you created in wx or in a separate application, for example, in notepad? If it is with wx, then it is trivial. You simply use Raise () to give the frame the focus you need. You would probably use PubSub or PostEvent so that the subframe knows what it needs to be raised.

, . , , 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/). - , script - . - MS Office, win32com SendKeys. .

+4

All Articles