c++ - Global keyboard hook with WH_KEYBOARD_LL and keybd_event (windows) -
i trying write simple global keyboard hook program redirect keys. example, when program executed, press 'a' on keyboard, program can disable , simulate 'b' click. not need graphic ui, console enough (keep running)
my plan use global hook catch key input, , use keybd_event simulate keyboard. have problems.
the first problem program can correctly block 'a' if hit 'a' on keyboard once, printf in callback function executed twice, keybd_event. if open txt file, click 'a' once, there 2 'b's input. why that?
the second question why hook using of wh_keyboard_ll can work on other process without dll? thought had use dll make global hook until wrote example...
#include "stdafx.h" #include <windows.h> #define _win32_winnt 0x050 lresult callback lowlevelkeyboardproc(int ncode, wparam wparam, lparam lparam) { bool featkeystroke = false; if (ncode == hc_action) { switch (wparam) { case wm_keydown: case wm_syskeydown: case wm_keyup: case wm_syskeyup: pkbdllhookstruct p = (pkbdllhookstruct)lparam; if (featkeystroke = (p->vkcode == 0x41)) { //redirect b printf("hello a\n"); keybd_event('b', 0, 0, 0); keybd_event('b', 0, keyeventf_keyup, 0); break; } break; } } return(featkeystroke ? 1 : callnexthookex(null, ncode, wparam, lparam)); } int main() { // install low-level keyboard & mouse hooks hhook hhklowlevelkybd = setwindowshookex(wh_keyboard_ll, lowlevelkeyboardproc, 0, 0); // keep app running until we're told stop msg msg; while (!getmessage(&msg, null, null, null)) { //this while loop keeps hook translatemessage(&msg); dispatchmessage(&msg); } unhookwindowshookex(hhklowlevelkybd); return(0); }
many thanks!
first 1 easy. 1 key down , key up. :)
as why can work without dll - that's because global hook. unlike thread-specific ones executed in own process, not in process keyboard event happened. done via message sending thread has installed hook - that's precisely why need message loop here. without hook can't ran there no 1 listen incoming messages.
the dll required thread-specific hooks because they're called in context of process. work, dll should injected process. not case here.
Comments
Post a Comment