by Richard Russell, October 2010
A hot key is a unique system-wide key combination which can be used to cause your program to take some action, irrespective of which application currently has the keyboard 'input focus'. Typically your program will be running invisibly 'in the background', biding its time until the appropriate keys are pressed.
The code listed below is a 'template' program which simply registers the associated hot key, and prints a message when it is detected. You should be able to expand it to perform any action(s) you wish.
Obviously, any particular hot key combination must be unique. Windows uses a first-come-first-served method; whichever program first registers a particular key combination will succeed, and subsequent programs which attempt to register that same combination will fail to do so. Try to choose an unusual key combination (the template program below uses Alt+ScrollLock).
If your program needs to respond to two or more different hot key combinations, you can specify different IDs; the ID is received in the @wparam% parameter of the WM_HOTKEY messages. The program below uses only one hot key, so does not bother to check the ID.
Most commonly you will want to compile your program with the 'Initial window state' set to hidden, and you may wish to start your program automatically by placing the executable in the Start Up folder, or creating an appropriate registry entry.
_MOD_ALT = &1 WM_HOTKEY = &312 VK_SCROLL = &91 ID% = 199 ON ERROR SYS "MessageBox", @hwnd%, REPORT$, 0, 0 : QUIT res% = FNregisterhotkey(@hwnd%, ID%, _MOD_ALT, VK_SCROLL) IF res%=0 ERROR 100, "Couldn't register Alt-ScrollLock as hot key" *SYS 1 ON SYS PROCsys(@msg%, @wparam%, @lparam%) : RETURN PRINT "Press Alt-ScrollLock..." REPEAT WAIT 1 UNTIL FALSE DEF PROCsys(M%, W%, L%) IF M% = WM_HOTKEY PRINT "Alt-ScrollLock pressed!" ENDPROC DEF FNregisterhotkey(hw%,id%,mod%,vk%) LOCAL M%, O%, P%, T% DIM P% LOCAL 54 [OPT 2 .T% push vk% push mod% push id% push hw% call "RegisterHotKey" ret 16 .M% cmp dword [esp+8],&500 : jz T% : jmp [^O%] ] SYS "GetWindowLong", @hwnd%, -4 TO O% SYS "SetWindowLong", @hwnd%, -4, M% SYS "SendMessage", @hwnd%, &500, 0, 0 TO T% SYS "SetWindowLong", @hwnd%, -4, O% SYS "SendMessage", @hwnd%, 0, 0, 0 = T%
Obviously if your program needs to respond to other ON SYS events it must check the appropriate @msg% value in PROCsys and act accordingly.