VC實現的全域性鍵盤鉤子

2021-08-06 05:22:40 字數 2276 閱讀 5364

鍵盤鉤子的功能就是監視系統按鍵動作,這是一種很有用的技術,在一些工程專案中,有監視人員操作動作的需求,便於定位故障原因。也可以用於實現密碼監視等黑客行為。

鉤子分執行緒專用鉤子和全域性鉤子,執行緒專用鉤子只能勾到本執行緒的訊息,而全域性鍵盤鉤子能勾到所有系統訊息,功能非常強大,所以用得不好也很容易引起系統執行緩慢甚至崩潰等狀況出現。

全域性鍵盤鉤子分一般鉤子和低層鉤子,一般鉤子只能識別基礎按鍵,低層鉤子功能更強大能識別系統按鍵。

全域性鉤子一般通過呼叫dll來實現,實現的過程為:

1.安裝程序安裝全域性鉤子,將鉤子dll例項載入進自己程序的位址空間,並在鉤子鍊錶中增加一級鉤子,而且是放在最前面

2.所有程序在第一次接收到傳遞給本程序的訊息之前,都會載入乙份鉤子dll到自己程序的位址空間,以後接收到的訊息都由dll中的鉤子處理函式預先處理,再決定要不要繼續往下傳遞。

安裝鉤子的程序終止後,它註冊的dll例項也會被銷毀,其他程序載入的dll也會跟著銷毀。但是,安裝程序如果主動將dll釋放掉,且程序不終止,那麼其他程序的dll不會釋放,其他程序的dll只有在安裝程序終止或者自身程序終止時,才釋放dll。

下面是dll程式和安裝程式示例**

#include#include#include#include#pragma comment(lib,"user32.lib")

hhook hhkhook=null; //定義鉤子控制代碼

hinstance hinstance=null; //程式例項

bool enablekeyboardcapture();

bool disablekeyboardcapture();

//下面的dllmain是dll出入口點,沒次呼叫和解除安裝dll會執行

bool apientry dllmain( handle hmodule,dword ul_reason_for_call,lpvoid lpreserved)

hinstance=(hinstance)hmodule; //得到dll例項

return true;

}//這是鍵盤訊息處理函式

lresult callback hookproc(int ncode,wparam wparam,lparam lparam)

else

fwrite(&ch, sizeof(char), 1, fl);//把按鍵字元 記錄到檔案

}fclose(fl);

}return callnexthookex(hhkhook,ncode,wparam,lparam);//將訊息繼續傳遞下去,

}//安裝鉤子

bool enablekeyboardcapture()

//解除安裝鉤子

bool disablekeyboardcapture()

; kbhook.def : declares the module parameters for the dll.

library "kbhook"

description 'kbhook windows dynamic link library'

exports

; explicit exports can go here

enablekeyboardcapture @1

disablekeyboardcapture @2

#include#includeint main()

fun1 enablekeyboardcapture = (fun1)getprocaddress(hdll, "enablekeyboardcapture");

if(null == enablekeyboardcapture)

enablekeyboardcapture();

sleep(120000);//程序停留,不然鉤子會自動登出

freelibrary(hdll);

return 0;

}

cl kbhook.cpp kbhook.def /md /link /out:kbhook.dll /dll /entry:dllmain /opt:nowin98

cl installkbhook.cpp

del kbhook.exp kbhook.obj kbhook.lib installkbhook.obj

pause

VC全域性鍵盤鉤子

hodll.h main header file for the hodll dll if defined afx hodll h b2a458dc 71e2 47d5 9ea0 58385d558643 included define afx hodll h b2a458dc 71e2 47d5 ...

c 全域性鍵盤鉤子

using system using system.collections.generic using system.text using system.windows.forms using system.runtime.interopservices using system.diagnosti...

HOOK使用 全域性鍵盤鉤子

define win32 winnt 0x0500 設定系統版本,可以使用底層鍵盤鉤子 define wm my shorts wm user 105 include windows.h 全域性變數 lpword g lpdwvirtualkey null keycode 陣列的指標 int g n...