1. 程式人生 > >SetWindowsHookEx 鉤子函式

SetWindowsHookEx 鉤子函式

 

 

#define EXPORT extern "C" _declspec(dllexport)

//可以指定成共享資料段  #pragma data_seg("shared") ....
HHOOK g_hook = NULL;

HINSTANCE g_dll = NULL;
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	g_dll = 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;
}


//唯一要注意的就是這個函數了
LRESULT CALLBACK keyProc(int    code,WPARAM wParam,LPARAM lParam)
{
    //見msdn
	if (code < 0)
		return CallNextHookEx(g_hook, code, wParam, lParam);

    //如果有鍵盤輸入
	if (HC_ACTION == code && lParam > 0){
        
		TCHAR buf[MAX_PATH];
        
        //看看是什麼按鍵
		GetKeyNameTextW(lParam, buf, MAX_PATH);
		MessageBox(NULL, buf, NULL, MB_OK);
	}
    
    //這行別忘記了 . 可以註釋掉看看
	return CallNextHookEx(g_hook, code, wParam, lParam);
}


//設定鍵盤鉤子
EXPORT void setHookOn()
{
	g_hook = SetWindowsHookEx(WH_KEYBOARD, keyProc, g_dll, 0);
}


EXPORT void setHookOff()
{
	UnhookWindowsHookEx(g_hook);
}