I'm trying to make a simple globalhook that prints some text into a .txt file whenever someone presses a key on the keyboard. The problem is that when I execute my program and press on a key in a certain program, the program gets stuck and doesn't respond anymore. So I think the problem is that the hookprocedure doesn't work/return properly when called.
this is the code in my .exe file:
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <wingdi.h>
#include <string>
using namespace std;
typedef bool (*install)();
install instal;
HINSTANCE hinst;
int main()
{
hinst = LoadLibrary(TEXT("injectdll.dll"));
if(!hinst)
{
printf("The DLL could not be found.\n");
}
instal = (install) GetProcAddress(hinst, "install");
if(!instal)
{
printf("The function was not found.\n");
}
if(!instal())
{
printf("func couldn't be executed");
}
printf("Program successfully hooked.\nPress enter to unhook the function and stop the program.\n");
getchar();
}
this is the code in my dll:
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <Strsafe.h>
using namespace std;
#pragma data_seg(".shared")
HHOOK hook = 0;
#pragma data_seg()
#pragma comment(linker, "/SECTION:.shared,RWS")
HINSTANCE hinst;
LRESULT CALLBACK meconnect(int code, WPARAM wParam, LPARAM lParam)
{
if (code < 0)
{
return CallNextHookEx(hook, code, wParam, lParam);
}
FILE *file;
fopen_s(&file, "function.txt", "a+");
fprintf(file, "Function keyboard_hook called.\n");
fclose(file);
return 0;
}
extern "C" __declspec(dllexport) bool install()
{
hook = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC) meconnect, hinst, 0);
return hook != NULL;
}
BOOL WINAPI DllMain(HINSTANCE hDLL, DWORD Reason, LPVOID Reserved) {
switch(Reason) {
case DLL_PROCESS_ATTACH:
hinst = hDLL;
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
the meconnect function returns 0, I don't know if this is right, but I also tried returning: return CallNextHookEx(hook, code, wParam, lParam); and return CallNextHookEx(0, code, wParam, lParam);
both didn't change anything in the results.