HOOK is a platform for message processing in Windows. Applications can set sub-programs to monitor certain messages or specific events (such as keyboard and mouse events) in a specified window ), the monitored window can be created by other processes. When a message arrives, process it before the target window processing function. The hook mechanism allows applications to intercept and process window messages or specific events.
The following is an example code that uses a keyboard HOOK to HOOK a keyboard. When the keyboard is captured and pressed, a sound is played.
# Include <windows. h> # include <tchar. h> # include <Mmsystem. h> # pragma comment (lib, "Winmm. lib "); HHOOK hHook; // lresult callback LowLevelKeyboardProc (int nCode, WPARAM wParam, LPARAM lParam); int APIENTRY _ tWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {MSG msg; // create a low-level keyboard hook hHook = SetWindowsHookEx (WH_KEYBOARD_LL, LowLevelKeyboardProc, hInstance, 0); // main message loop: while (GetMessage (& msg, NULL, 0, 0); // uninstall the low-level keyboard hook UnhookWindowsHookEx (hHook); return (int) msg. wParam;} // lresult callback (int nCode, WPARAM wParam, LPARAM lParam) {KBDLLHOOKSTRUCT * kbllHookStruct = (KBDLLHOOKSTRUCT *) lParam; // if you press the button if (wParam = WM_KEYDOWN) {// play the sound PlaySound (_ T ("shake.wav"), NULL, SND_FILENAME | SND_ASYNC );} TCHAR str [255] = {0}; _ stprintf (str, _ T ("Msg Code = 0x % x, vkCode = % d \ n"), wParam, kbllHookStruct-> vkCode); OutputDebugString (str); // send the Keyboard Message to the next hook return CallNextHookEx (hHook, nCode, wParam, lParam );}