ZT文萃

本博不原创,转帖自己感兴趣那些事人物,什么入眼贴什么,随心所欲。
posts - 93, comments - 5, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

c#键盘钩子

Posted on 2013-11-13 14:21 ZT文萃 阅读(207) 评论(0)  编辑  收藏 所属分类: 前台
http://wuqinzhong.blog.163.com/blog/static/45222312009101711583439/

c#键盘钩子  

2009-11-17 11:58:34|  分类: C# |字号 订阅

c#键盘钩子:

    public class Win32Hook
    {

        [DllImport("kernel32")]
        public static extern int GetCurrentThreadId();

        [DllImport("user32",CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(HookType idHook, HOOKPROC lpfn, int hmod, int dwThreadId);
        [DllImport("user32", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int hhk,int nCode,int wParam,int lParam);
        [DllImport("user32", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnHookWindowsHookEx(int hhk);

        public enum HookType
        {
            WH_KEYBOARD = 2
        }

        public delegate int HOOKPROC(int nCode, int wParam, int lParam);
        public int hhk;

        public void SetHook()
        {
            // set the keyboard hook
            hhk = SetWindowsHookEx(HookType.WH_KEYBOARD, new HOOKPROC(this.MyKeyboardProc), 0, GetCurrentThreadId());
        }

        public int MyKeyboardProc(int nCode, int wParam, int lParam)
        {
            //在这里放置你的处理代码
            int iresult = 0;
            if (nCode<=0)
            {
                iresult = CallNextHookEx(hhk, nCode, wParam, lParam);
                return iresult;
            }
            if ((wParam >= 48 && wParam<=57)||(wParam >= 65 && wParam<=90)||(wParam >= 97 && wParam<=122))
            {
                Form1.rrrr += Convert.ToChar(wParam);
                return 0;
            }

            return 0;
        }
        public bool UnHook()
        {
           return UnHookWindowsHookEx(hhk);
        }

    }

使用:

Win32Hook hook = new Win32Hook();
            hook.SetHook();

            this.richTextBox2.Text = rrrr;
            hook.UnHook();

参考:http://baike.baidu.com/view/1208620.htm

使用参照:http://www.codeproject.com/KB/system/globalsystemhook.aspx

             (adamhtmei)


只有注册用户登录后才能发表评论。


网站导航: