鍵盤鉤子是一種可以監控鍵盤操作的指令,我們去釣魚只要魚兒上鉤不管它怎麼逃,只要掌控好鉤子上的繩子總是可以找到這條魚,鍵盤鉤子是利用電腦一行行執行代碼特性,在目的視窗處理鍵代碼前攔截把某個指令替換為另外一種指令,然後再把訊息傳送給目的視窗這樣一個周期下來,視窗程序會認為使用者輸入的就是現在的數值或者沒有輸入,不過鍵盤鉤子在某些不法分子手裡則成為了 盜號、監控密碼 等違法操作。原型:HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, HINSTANCE hMod, DWORD dwThreadId);
// Win32 keyboard hook.public const int WH_KEYBOARD_LL = 13;public const int NULL = 0; public delegate int HookProc(int code, int wParam, KBDLLHOOKSTRUCT lParam); [DllImport("user32.dll", SetLastError = true)]public static extern int SetWindowsHookEx(int hookType, HookProc lpfn, int hMod, int dwThreadId); [DllImport("User32.dll", SetLastError = true)]public extern static int CallNextHookEx(int handle, int code, int wParam, KBDLLHOOKSTRUCT lParam); [StructLayout(LayoutKind.Sequential)]public class KBDLLHOOKSTRUCT{ public uint vkCode; public uint scanCode; public KBDLLHOOKSTRUCT flags; public uint time; public UIntPtr dwExtraInfo;} [Flags]public enum KBDLLHOOKSTRUCT : uint{ LLKHF_EXTENDED = 0x01, LLKHF_INJECTED = 0x10, LLKHF_ALTDOWN = 0x20, LLKHF_UP = 0x80,} public volatile int hHook; protected override void OnLoad(EventArgs e){ base.OnLoad(e); // 安裝全域鍵盤鉤子 if ((this.hHook = SetWindowsHookEx(WH_KEYBOARD_LL, this.KeyBoardProc, NULL, NULL)) == NULL) Console.WriteLine("Unable to establish a keyboard hook.");} protected int KeyBoardProc(int code, int wParam, KBDLLHOOKSTRUCT lParam){ if (lParam.vkCode == (int)Keys.A) return 1; // 返回1表示攔截訊息,返回0表示允許存取 return CallNextHookEx(hHook, code, wParam, lParam);}
監控系統內所有進程鍵盤訊息:
SetWindowsHookEx(WH_KEYBOARD_LL, KeyBoardProc, NULL, NULL)
// Win32 keyboard hook. public const int WH_KEYBOARD = 2; public const int NULL = 0; public delegate int HookProc(int code, int wParam, int lParam); [DllImport("kernel32.dll", SetLastError = true)] public static extern int GetCurrentThreadId(); [DllImport("user32.dll", SetLastError = true)] public static extern int SetWindowsHookEx(int hookType, HookProc lpfn, int hMod, int dwThreadId); [DllImport("User32.dll", SetLastError = true)] public extern static int CallNextHookEx(int handle, int code, int wParam, int lParam); public volatile int hHook; protected override void OnLoad(EventArgs e) { base.OnLoad(e); // 安裝鍵盤鉤子
if ((this.hHook = SetWindowsHookEx(WH_KEYBOARD, KeyBoardProc, NULL, GetCurrentThreadId())) == NULL) Console.WriteLine("Unable to establish a keyboard hook."); }
protected int KeyBoardQueue(int code, int wParam, int lParam){ if (wParam == (int)Keys.A) return 1; // 返回1表示攔截訊息,返回0表示允許存取 return CallNextHookEx(hHook, code, wParam, lParam);}
監控本進程的所有鍵盤訊息:
SetWindowsHookEx(WH_KEYBOARD, KeyBoardProc, NULL, GetCurrentThreadId());
protected int KeyBoardProc(int code, int wParam, int lParam) { if (wParam == (int)Keys.A) return 1; return CallNextHookEx(hHook, code, wParam, lParam); }