windows mobile 键盘钩子 屏蔽按键
扫描二维码
随时随地手机看文章
封装好的类,直接添加到工程中就可以使用。
注意: 这种方式可能会出一些意想不到的问题,比如在windows mobile平台,直接在C#程序中使用coredll.dll的钩子,可能导致cursor显示不正常,C#程序中启动新的其他进程,返回时点按键可能导致程序卡死等其他问题,虽然方便,但不建议如此使用钩子。建议的方式是用C++编译一个钩子程序,在C#程序中调用,这样,钩子和C#程序不在一个进程中,安全性更高一些。
/*这个类是用来屏蔽相关按键的,你可以new一个这个类的实例,然后调用相关的public方法就可以了,在C#程序中,你要在程序开始的位置调用,也就是Main函数中的窗体创建语句前调用开始钩子函数。在Main函数结束的位置再调用钩子关闭函数。将你想屏蔽的按键的键值添加到对应的位置,注释里面有解释,请查看。*/ 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) { //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 { //处理相关代码,需要屏蔽的按键在此case switch (m.vkCode) { case (int)KeyValueMap.VK_TEND: //屏蔽掉挂断键 case (int)KeyValueMap.VK_TTALK: { return 1; } } } } return CallNextHookEx(hKeyboardHook, nCode, wParam,ref lParam); } }