#define WH_KEYBOARD_LL 13
#define WH_MOUSE_LL 14
#define MB_ICONERROR 0x00000010L
typedef void *HHOOK;
typedef struct tagKBDLLHOOKSTRUCT {
DWORD vkCode;
DWORD scanCode;
DWORD flags;
DWORD time;
long dwExtraInfo;
// ULONG_PTR dwExtraInfo;
} KBDLLHOOKSTRUCT; //, FAR *LPKBDLLHOOKSTRUCT, *PKBDLLHOOKSTRUCT;
KBDLLHOOKSTRUCT *pKbdStruct;
// Callback function (called when a key is pressed)
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
// the action is valid: HC_ACTION.
if (wParam == WM_KEYDOWN) {
// lParam is the pointer to the struct containing the data needed, so cast and assign it to kdbStruct
pKbdStruct = (KBDLLHOOKSTRUCT*)lParam;
// kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
// a key (non-system) is pressed.
if (pKbdStruct.vkCode == VK_F1) {
// F1 is pressed!
MessageBox(NULL, "F1 is pressed!", "key pressed", MB_ICONINFORMATION);
}
}
}
// call the next hook in the hook chain. This is nessecary or your hook chain will break and the hook stops
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
void SetHook() {
// Set the hook and set it to use the callback function above
// WH_KEYBOARD_LL means it will set a low level keyboard hook. More information about it at MSDN.
// The last 2 parameters are NULL, 0 because the callback function is in the same thread and window as the
// function that sets and releases the hook. If you create a hack you will not need the callback function
// in another place then your own code file anyway. Read more about it at MSDN.
if (!(_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0))) {
MessageBox(NULL, "Failed to install hook!", "Error", MB_ICONERROR);
}
}
void ReleaseHook() {
UnhookWindowsHookEx(_hook);
}
void init_startup () {
// Set the hook
SetHook();
on_close = ReleaseHook;
on_exit = ReleaseHook;
}