返回> 网站首页
Windows Mobile C#按键钩子
yoours2014-07-23 14:08:26
简介一边听听音乐,一边写写文章。
using System.Runtime.InteropServices; using System; 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 6.5下使用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 = "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_ESCAPE = 0x1B, //ESC VK_RETURN = 0x0D, //RETURN,回车 VK_APP5 = 0xC5, //蓝色FN VK_APP2 = 0xC2, //黄色FN VK_APP1 = 0xC1, //WIN,菜单键 VK_TEND = 0x73, //End,挂断键 VK_TTALK = 0x72, //Talk,拨号键 VK_TVOLUMEUP = 0x75, //音量+ VK_TVOLUMEDOWN = 0x76,//音量- VK_BACK = 0x08, //BKSP VK_SHIFT = 0x10, //SHIFT VK_TAB = 0x09, //TAB VK_TSTAR = 0x77, //*,星号 VK_TPOUND = 0x78, //#,井号 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) { //wParam用于判断是按键按下还是弹起 //Keys keyData = (Keys)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) { switch (m.vkCode) { case (int)KeyValueMap.VK_TEND://屏蔽掉挂断键 case (int)KeyValueMap.VK_TTALK: { return 1; } } } } return CallNextHookEx(hKeyboardHook, nCode, wParam, ref lParam); } } |
文章评论
1771人参与,0条评论