Close

Simple global keyboard hook

A project log for Cheap Windows Jog/keyboard controller for CNCs

Cheap <$5 usb numpad to use for key macros and CNC job controllers. Primarily I'm using it to extend a remote for jogging around my G0704

charliexcharliex 04/21/2015 at 22:590 Comments

Make a win32 console project in Visual Studio or so.

add windows.h

in main() add

printf ( "setting global hook\n" );

// Insert a low level global keyboard hook
HHOOK hook_keyboard = SetWindowsHookEx ( WH_KEYBOARD_LL, ll_keyboardproc, 0, 0 );

// now just the windows message pump
MSG msg;
while ( !GetMessage ( &msg, NULL, NULL, NULL ) ) {
 TranslateMessage ( &msg );
 DispatchMessage ( &msg );
}

// unhook keyboard hook
UnhookWindowsHookEx ( hook_keyboard );

add this function, this gets called on every key press, up and down events (some keys need special handling)

/**
* ll_keyboardproc
*/
LRESULT CALLBACK ll_keyboardproc ( int nCode, WPARAM wParam, LPARAM lParam )
{
// if keyup event , gets set to keyup flag
int keyup = 0;

// are we replacing/removing the key
bool replace_key = false;

// process it, if its an HC_ACTION otherwise pass on to OS
if ( nCode == HC_ACTION ) {
// key up/down etc
switch ( wParam ) {

case WM_KEYUP:
case WM_SYSKEYUP:
keyup = KEYEVENTF_KEYUP;
// falls thru
case WM_KEYDOWN:
case WM_SYSKEYDOWN:

PKBDLLHOOKSTRUCT p = ( PKBDLLHOOKSTRUCT ) lParam;
switch ( p->vkCode ) {

//  process individual keys
case 'Q':
// send our replacement key (as an up or down message)
keybd_event ( 'Z', 0, keyup, 0 );
//remove the original key press
replace_key = true;
break;

case 'Z':
keybd_event ( 'Q', 0, keyup, 0 );
replace_key = true;
break;
default:
break;
}
break;
}
}

// pass on to OS
if( replace_key == false ) {
return CallNextHookEx ( NULL, nCode, wParam, lParam ) ;
}

// remove the original key press.
return 1;

}

formatting gets removed in the code box.

this will replace Q with Z and Z with Q, or q/z. You could also do something else, call a function, run an exe, output a digital line etc. Obviously this is also a simple key logger, you can also send multiple key presses, so now its a macro playback etc. there is some additional logic for sys keys etc, but keeping it simple.

so pretty simple, install a global keyboard hook and process the messages. this would work if you had one keyboard and wanted to remap the keys, but it is less useful.

next is using RAWINPUT to determine where the key came from

Discussions