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?
Python

Avatar of undefined
Last Comment
yokai

8/22/2022 - Mon
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
RichieHindle

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
yokai

ASKER
Richie,

Works great, but how to I unregister it? :)
RichieHindle

Like this:
user32.UnregisterHotKey(None, hotkeyId)

Open in new window

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
yokai

ASKER
Thank you!!