封裝好的類,直接添加到工程中使用。
public class KeyBoardHookClass { public delegate int HookProc(int nCode, int wParam,ref KeyMSG lParam); //聲明代理,用於回呼函數 private static int hKeyboardHook = 0; private HookProc KeyboardHookProcedure; //win32下使用user32.dll windows mobile 下使用coredll.dll //設定鉤子 [DllImport("coredll.dll",EntryPoint = "SetWindowsHookEx")] public static extern int SetWindowsHookEx(HookType idHook, HookProc lpfn, IntPtr hInstance, int threadId); //抽調鉤子 [DllImport("coredll.dll", EntryPoint = "UnhookWindowsHookEx")] public static extern bool UnhookWindowsHookEx(int idHook); [DllImport("coredll.dll", EntryPoint = "GetCurrentThreadId")] public static extern int GetCurrentThreadId(); [DllImport("coredll.dll", EntryPoint = "GetModuleHandle")] public static extern IntPtr GetModuleHandle(string name); [DllImport("coredll.dll", EntryPoint = "CallNextHookEx")] public static extern int CallNextHookEx(int idHook, int nCode, int wParam, ref KeyMSG lParam); //鉤子類型 public enum HookType { WH_KEYBOARD = 2, WH_KEYBOARD_LL = 20 } //索引值枚舉 public enum KeyValueMap : int { VK_TEND = 0x73, // 掛斷鍵 VK_TTALK = 0x72, //撥號鍵 WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105 } //鍵盤結構 public struct KeyMSG { public int vkCode; //索引值 public int scanCode; public int flags; public int time; public int dwExtraInfo; } public void StartHook() { //安裝鍵盤鉤子 try { KeyboardHookProcedure = new HookProc(KeyboardHookProc); hKeyboardHook = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, KeyboardHookProcedure, IntPtr.Zero, 0); } catch (Exception ex) { StopHook(); throw new Exception(ex.ToString() + "安裝鉤子失敗."); } } public void StopHook() { try { UnhookWindowsHookEx(hKeyboardHook); } catch (Exception ex) { throw new Exception(ex.ToString() + "卸下鉤子失敗."); } } //鉤子回呼函數 private int KeyboardHookProc(int nCode, int wParam, ref KeyMSG lParam) { if (nCode >= 0) { //Keys keyData = (Keys)wParam; //wParam用於判斷是按鍵按下還是彈起 KeyMSG m = (KeyMSG)lParam; if (wParam == (int)KeyValueMap.WM_KEYDOWN || wParam == (int)KeyValueMap.WM_KEYUP || wParam == (int)KeyValueMap.WM_SYSKEYDOWN || wParam == (int)KeyValueMap.WM_SYSKEYUP) //key down { //處理相關代碼 switch (m.vkCode) { case (int)KeyValueMap.VK_TEND: //屏蔽掉掛斷鍵 case (int)KeyValueMap.VK_TTALK: { return 1; } } } } return CallNextHookEx(hKeyboardHook, nCode, wParam,ref lParam); } }