This is my C++ code:
#include <iostream>
#include <windows.h>
HHOOK hook;
LRESULT CALLBACK keyboardHook(int nCode, WPARAM wParam, LPARAM lParam)
{
std::cout << "Hook callback" << std::endl;
return CallNextHookEx(hook, nCode, wParam, lParam);
}
int main(int argc, char **argv)
{
hook = SetWindowsHookEx(WH_KEYBOARD, keyboardHook, NULL, NULL);
if (hook == NULL) {
std::cout << "Error " << GetLastError() << std::endl;
return 1;
}
std::cout << "Hook set" << std::endl;
}
I compile it using Visual Studio like this:
cl /D_WIN32_WINNT=0x0401 foo.cc /link user32.lib
When I run it, I get error 1428.
C:\>foo.exe
Error 1428
This is the meaning of error 1428.
C:\nocaps>net helpmsg 1428
Cannot set nonlocal hook without a module handle.
Could you please help me to understand this error and get this code working? It would be great if you could provide me a working code that works and invokes the callback?
I see that if I use WH_KEYBOARD_LL hook instead, it works fine. But I need to understand how WH_KEYBOARD hook can be made to work.
keyboardHookfunction cannot be in the same EXE as themainfunction because thekeyboardHookfunction needs to be in a separate DLL. Have I understood it correctly?NULLand 0 as the last two arguments toSetWindowsHookExmight result in an error.NULLis not the current module.GetModuleHandle(NULL)is.