I am looking to write a keyboard hook for a c++ project. I found some code but dont want to use it without fully understanding it:
HHOOK _hook;
KBDLLHOOKSTRUCT kbdStruct;
LRESULT __stdcall HookCallback(int ncode, WPARAM wParam, LPARAM lparam)
{
if(ncode>=HC_ACTION)
{
if((wParam == WM_KEYDOWN) || (wParam == WM_SYSKEYDOWN))
{
kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
DWORD dwMsg = 1;
dwMsg += kbdStruct.scanCode << 16;
dwMsg += kbdStruct.flags << 24;
char key[16];
GetKeyNameText(dwMsg,key,15);
if((GetKeyNameState(VK_CAPITAL)& 0x0001) == 0)
{
for (int i=0; i<10)key[i] = tolower(key[i]);
ReturnKeyPressed(key);
}
else
{
ReturnKeyPressed(key);
}
}
}
return CallNextHookEx(_hook,nCode,wParam,lParam);
}
void SetHook()
{
_hook = SetWindowsHookEx(WH__KEYBOARD_LL,HookCallback,Null,0);
}
I dont understand what nCode is here. And where do the other parameters come from? Greeting from an absolute C++ beginner :).
In a nutshell, nCode tells you whether the wParam and lParam contain valid data or not. If nCode is HC_ACTION (0), then they do, otherwise they do not. This is clearly stated in the documentation:
nCode [in]
Type:intA code the hook procedure uses to determine how to process the message. If nCode is less than zero, the hook procedure must pass the message to the
CallNextHookExfunction without further processing and should return the value returned byCallNextHookEx. This parameter can be one of the following values.HC_ACTION
0The
wParamandlParamparameters contain information about a keyboard message.wParam [in]
Type:WPARAMThe identifier of the keyboard message. This parameter can be one of the following messages:
WM_KEYDOWN,WM_KEYUP,WM_SYSKEYDOWN, orWM_SYSKEYUP.lParam [in]
Type:LPARAMA pointer to a
KBDLLHOOKSTRUCTstructure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With