Hi, so I have a dll that gets called by the main process and I would like to check for any keyboard input that is happening in the main process within the dll by using the
This is roughly how the dll looks like:
static HHOOK hhk = NULL;
LRESULT CALLBACK keyboardProc(int code, WPARAM wParam, LPARAM lParam)
if(code == HC_ACTION && ((DWORD)lParam & 0x80000000) == 0) // if there is an incoming action and a key was pressed
printf("Space was pressed\n");
return CallNextHookEx(hhk, code, wParam, lParam);
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
if(ul_reason_for_call == DLL_PROCESS_ATTACH)
freopen("CONOUT$", "w", stdout); // redirect output to console for debugging
printf("Dll loaded, lastError = %i\n", GetLastError());
printf("lastError = %i\n", GetLastError());
// sidenote: for some reason the first GetLastError() returns 0 while the second one returns 6 (invalid handle)
hhk = SetWindowsHookEx(WH_KEYBOARD, keyboardProc, hModule, NULL);
else if (ul_reason_for_call == DLL_PROCESS_DETACH)
Now when I start up the program, everything is loading fine and it even works like I want it when I keep the program focused (which means every time I press "Space", the message gets printed in that console).
However for some reason when I switch the focus to another program or even to the console where the output is printed then every time I press a key, the
function in the hook is called with
ul_reason_for_call = DLL_PROCESS_ATTACH
That means when I press any key somewhere else, a new console window is allocated and when I put the focus on the window from where I previously pressed that key and press "Space" there, the message is written in the newly created console.
So my question is, why is this happening (or what am I doing wrong) and how do I fix it?