1. 程式人生 > >全局鍵盤鉤子

全局鍵盤鉤子

call ++ http void export eof one rtu 資料

記得幾年前學習windows開發的時候,為了一個鍵盤鉤子在網上找了無數的資料也沒幾個能用的。

最近又需要用到全局鍵盤鉤子記錄鍵盤消息,發現一篇不錯的文章。

http://blog.csdn.net/one_six_mix/article/details/52044406

使用SetWindowsHookEx 設置鉤子,但是全局鉤子必須要使用dll。

新建一個dll,將以下代碼復制:

LPWORD      g_lpdwVirtualKey = NULL;    //Keycode 數組的指針   
int         g_nLength = 0;          //Keycode 數組的大小   
HINSTANCE   g_hInstance = NULL;     //模塊實例句柄    
HHOOK       g_hHook = NULL;         //鉤子句柄   
HWND        g_hWnd  = NULL;    

BOOL APIENTRY DllMain(HANDLE hModule,DWORD  ul_reason_for_call,LPVOID lpReserved)
{
    //保存模塊實例句柄   
    g_hInstance = (HINSTANCE)hModule;   
	
    //在進程結束或線程結束時卸載鉤子    
    switch (ul_reason_for_call)   
    {   
    case DLL_PROCESS_ATTACH:   
		break;    
    case DLL_THREAD_ATTACH:  
		break;       
    case DLL_PROCESS_DETACH:   
	case DLL_THREAD_DETACH:    
        delete g_lpdwVirtualKey;    
        if (g_hHook != NULL) UnhookWindowsHookEx(g_hHook);   
        break;  
    }  
    return TRUE;  
}

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam,LPARAM lParam)  
{
	if((HC_ACTION == nCode && lParam & 0x40000000) || (wParam==16) || wParam == 20){
		FILE *fp = fopen("E:\\key.txt","a+");
		if(fp == NULL) fp = fopen("E:\\key.txt","w+");
		
		char msg[20];
		ZeroMemory(msg,20);
		sprintf(msg,"%d %02X\r\n",wParam,lParam);
		fputs(msg,fp);
		fclose(fp);
	}

    return CallNextHookEx(g_hHook, nCode, wParam, lParam);   
}    

_declspec(dllexport)  BOOL WINAPI StartCatch(HWND  pWnd)   
{    
    g_hWnd = pWnd;    
    //如果已經安裝鍵盤鉤子則返回 FALSE    
    if (g_hHook != NULL) return FALSE;  
    //將用戶傳來的 keycode 數組保存在全局變量中   
    /*g_lpdwVirtualKey = (LPWORD)malloc(sizeof(WORD) * nLength);   
    LPWORD tmpVirtualKey = g_lpdwVirtualKey;   
    for (int i = 0; i < nLength; i++)    
    {   
        *tmpVirtualKey++ = *lpdwVirtualKey++;   
    }   
    g_nLength = nLength;   */ 
    //安裝底層鍵盤鉤子
    g_hHook = SetWindowsHookEx(WH_KEYBOARD, LowLevelKeyboardProc,  g_hInstance, NULL);    
    if (g_hHook == NULL) return FALSE;   
    return TRUE;    
}    

_declspec(dllexport)  BOOL WINAPI StopCatch()   
{   //卸載鉤子   
    if (UnhookWindowsHookEx(g_hHook) == 0) return FALSE;   
    g_hHook = NULL;   
    return TRUE;   
}    

可以看到這個dll裏導出了兩個函數

_declspec(dllexport) BOOL WINAPI StartCatch(HWND pWnd)

_declspec(dllexport) BOOL WINAPI StopCatch()

新建一個程序,調用StartCatch開啟鉤子,StopCatch關閉鉤子。

全局鍵盤鉤子