07-24-2012, 12:26 PM
A simple keyboard remapping function with a hook.
Function remap_keyboard
Function remap_keyboard_hook
Function remap_keyboard_my_map
Function remap_keyboard
;Run this function to turn on remapping. Run again to turn off.
;if already running, end the thread and exit
if getopt(nthreads)>1
,shutdown -6 0 "remap_keyboard"
,ret
;set hook and wait
int keyhook=SetWindowsHookEx(WH_KEYBOARD_LL &remap_keyboard_hook _hinst 0)
MessageLoop ;;need to process messages
UnhookWindowsHookEx keyhookFunction remap_keyboard_hook
;/remap_keyboard
function nCode wParam KBDLLHOOKSTRUCT&h
;This function runs as a hook procedure, called by Windows on each key down and up event.
if(nCode!=HC_ACTION) goto gRet ;;normally always HC_ACTION
if(h.flags&LLKHF_INJECTED) goto gRet ;;sent by a macro, not by the user
;call a function that returns a nonempty value if remapping needed for this key
VARIANT v=remap_keyboard_my_map(h)
if v.vt ;;remapping found
,;send the remap-key and "eat" the source-key
,int up=h.flags&LLKHF_UP
,opt keysync 1 ;;minimal synchronization; recommended in functions like this
,sel v.vt
,,case VT_I4 ;;virtual-key code etc
,,if(!up) key+ (v.lVal); else key- (v.lVal)
,,
,,case VT_BSTR ;;text
,,if(!up) _s=v; key (_s)
,,
,ret 1 ;;return 1 means "eat" the event, ie not pass to the foreground window as well as to other hooks
;gRet
ret CallNextHookEx(0 nCode wParam &h) ;;need this, otherwise other hooks (eg QM keyboard triggers) will not receive the eventFunction remap_keyboard_my_map
;/remap_keyboard
function` KBDLLHOOKSTRUCT&h
;Edit this function to create your remapping.
;h - contains user-pressed key info. Don't change it.
;If you want to remap this key, let this function return the remapping:
;;;To remap to a key, return the virtual-key code.
;;;To remap to a string (eg a character), return the string.
;You can also edit this function while remap_keyboard thread is running. To apply, click Save or Compile button. On syntax error remap_keyboard thread will end. You can run this function (click Run button) to launch remap_keyboard.
int up=h.flags&LLKHF_UP ;;0 down, 1 up
;;debug. Shows pressed keys, their virtual-key codes and scancodes. Disable when not needed.
FormatKeyString h.vkCode 0 &_s
out "%s %s, vk=0x%X, sc=0x%X%s" _s iif(up "up " "down") h.vkCode h.scanCode iif(h.flags&LLKHF_EXTENDED ", extended" "")
;Examples:
;remap using scancodes; scancodes represent physical keys
sel h.scanCode
,case 0x5C ret VK_DELETE ;;WinR to Delete
,case 0xD ret "''" ;;key += to character "
,;...
;;remap using virtual-key codes; virtual-key codes represent logical keys on current keyboard layout; look for the table in QM Help
sel h.vkCode
,case 'Q' ret 'W' ;;key Q to W
,case 'W' ret 'Q' ;;key W to Q
,;...
#ret ;;everything you'll type below will not be included in the macro. Eg you can type any text here when testing.