我正在尝试制作一个简单的全局挂钩,只要有人按下键盘上的键,它就会将一些文本打印到 .txt 文件中。问题是,当我执行我的程序并按下某个程序中的某个键时,程序会卡住并且不再响应。所以我认为问题在于钩子程序在调用时无法正常工作/返回。
这是我的 .exe 文件中的代码:
#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();
}
这是我的 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;
}
meconnect函数返回0,不知道对不对,不过我也试过返回:return CallNextHookEx(hook, code, wParam, lParam); 并返回 CallNextHookEx(0, code, wParam, lParam);
两者都没有改变结果。