Link to home
Start Free TrialLog in
Avatar of yokai
yokai

asked on

Create Hot Key?

I would like to keep a script running in the background that allows me to launch a subprocess at the press of a hot key combo (i.e. Ctrl+F5).  Is this possible with Python?
Avatar of RichieHindle
RichieHindle

Here you go:
import os, sys
from ctypes import *
from ctypes.wintypes import *
 
user32 = windll.user32
 
WM_HOTKEY   = 0x0312
MOD_ALT     = 0x0001
MOD_CONTROL = 0x0002
MOD_SHIFT   = 0x0004
 
class MSG(Structure):
    _fields_ = [('hwnd', c_int),
                ('message', c_uint),
                ('wParam', c_int),
                ('lParam', c_int),
                ('time', c_int),
                ('pt', POINT)]
 
# Register a hotkey for Ctrl+Shift+Z.
hotkeyId = 1
if not user32.RegisterHotKey(None, hotkeyId, MOD_CONTROL | MOD_SHIFT, ord('Z')):
    sys.exit("Failed to register hotkey; maybe someone else registered it?")
 
# Spin a message loop waiting for WM_HOTKEY.
while 1:
    msg = MSG()
    while user32.GetMessageA(byref(msg), None, 0, 0) != 0:
        if msg.message == WM_HOTKEY and msg.wParam == hotkeyId:
            os.spawnl(os.P_NOWAIT, r"c:\windows\notepad.exe")
        user32.TranslateMessage(byref(msg))
        user32.DispatchMessageA(byref(msg))

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of RichieHindle
RichieHindle

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of yokai

ASKER

Richie,

Works great, but how to I unregister it? :)
Like this:
user32.UnregisterHotKey(None, hotkeyId)

Open in new window

Avatar of yokai

ASKER

Thank you!!