首頁 > 後端開發 > C#.Net教程 > C# 鍵盤鉤子

C# 鍵盤鉤子

大家讲道理
發布: 2016-11-10 10:02:25
原創
2132 人瀏覽過

          鍵盤鉤子是一種可以監控鍵盤操作的指令,我們去釣魚只要魚兒上鉤不管它怎麼逃,只要掌控好鉤子上的繩子總是可以找到這條魚,鍵盤鉤子是利用電腦一行行執行程式碼特性,在目的視窗處理鍵代碼前攔截把某個指令替換為另外一種指令,然後再把消息傳送給目的窗口這樣一個週期下來,窗口程序會認為用戶輸入的就是現在的數值或者沒有輸入,不過鍵盤鉤子在某些不法分子手中則成為了盜號、監控密碼等違法操作。原型: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; // <span style="font-family: arial, 宋体, sans-serif;font-size:18px; line-height: 24px; text-indent: 28px;">返回1表示拦截消息,返回0表示放行</span>
    return CallNextHookEx(hHook, code, wParam, lParam);
}
登入後複製

監控系統內所有進程鍵盤訊息:
   本進程的所有鍵盤訊息:

     SetWindowsHookEx(WH_KEYBOARD, KeyBoardProc, NULL, GetCurrentThreadId());

<pre name="code" class="csharp">        // 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);
<pre name="code" class="csharp" style="line-height: 24px;font-size:18px;">            // 安装键盘钩子
登入後複製

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板