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
SetWindowsHookEx
function.
This is roughly how the dll looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
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
{
switch(wParam)
{
case VK_SPACE:
printf("Space was pressed\n");
break;
default:
break;
}
}
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)
{
if(AllocConsole()){
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)
{
printf("\nCleaning up...");
FreeConsole();
UnhookWindowsHookEx(hhk);
}
return TRUE;
}
| |
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
DllMain()
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?