Winform 通過鉤子監控鍵盤操作和滑鼠移動

2021-08-22 19:47:42 字數 1833 閱讀 3295

從網上找的乙個解決辦法,可以通過鉤子的方式實現,這裡記錄一下。

/// ///監控鍵盤鉤子

///

public class keyboardhook

[dllimport("kernel32.dll")]

public static extern intptr getmodulehandle(string lpmodulename);

//安裝鉤子

[dllimport("user32.dll", charset = charset.auto, callingconvention = callingconvention.stdcall)]

public static extern int setwindowshookex(int idhook, hookproc lpfn, intptr hinstance, int threadid);

//下乙個鉤子

[dllimport("user32.dll", charset = charset.auto, callingconvention = callingconvention.stdcall)]

public static extern int callnexthookex(int idhook, int ncode, int32 wparam, intptr lparam);

//解除安裝鉤子

[dllimport("user32.dll", charset = charset.auto, callingconvention = callingconvention.stdcall)]

public static extern bool unhookwindowshookex(int idhook);

private int keyboardhookproc(int ncode, int32 wparam, intptr lparam)

}return callnexthookex(hkeyboardhook, ncode, wparam, lparam);

}public void start()}}

public void stop()

if (!retkeyboard)

throw new exception("unload globalkeyboardhook failed!");

}//建構函式中安裝鉤子

public keyboardhook()

//析構函式中解除安裝鉤子

~keyboardhook()

}

按 ctrl+c 複製**

按 ctrl+c 複製**

使用

public partial class form1 : form

keyboardhook key = new keyboardhook();

mousehook mouse = new mousehook();

private void form1_load(object sender, eventargs e)

void form1_formclosing(object sender, formclosingeventargs e)

void key_onkeydownevent(object sender, system.windows.forms.keyeventargs e)

void mouse_onmouseactivity(object sender, system.windows.forms.mouseeventargs e)

}

測試

最小化到工作列之後

原文

C 鍵盤鉤子

鍵盤鉤子是一種可以監控鍵盤操作的指令,我們去釣魚只要魚兒上鉤 不管它怎麼逃,只要掌控好鉤子上的繩子總是可以找到這條魚,鍵盤 鉤子是利用電腦一行行執行 特性,在目的視窗處理鍵 前攔截 把某個指令替換為另外一種指令,然後再把訊息傳送給目的視窗這樣 乙個週期下來,視窗程式會認為使用者輸入的就是現在的數值或...

C winform鍵盤鉤子

新建乙個工程csharpkeyboardhook,在winform窗體上拉乙個lable 用於顯示,按下的是那個鍵 和兩個button 用於開關勾子 下面是c winform鍵盤勾子的 照搬上去就可以的啦 一 新建乙個類檔案keyboardhooklib,如下所示 using system usin...

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 ...