首页 > 代码库 > 热键HotKeys

热键HotKeys

一:新建类HotKeys命名空间:

using System.Runtime.InteropServices;

二:注册热键API

[DllImport("user32")]
public static extern bool RegisterHotKey(IntPtr hWnd, Int32 id, UInt32 fsModifilters, Keys key);
[DllImport("user32")]
public static extern bool UnregisterHotKey(IntPtr hWnd, Int32 id);

三:注册/注销热键

       public static void RegHotKey(IntPtr ptr)
        {
            RegisterHotKey(ptr, 555, 0, Keys.F5);
            RegisterHotKey(ptr, 666, 0, Keys.F6);
        }
        public static void UnRegHotKey(IntPtr ptr)
        {
            UnregisterHotKey(ptr, 555);
            UnregisterHotKey(ptr, 666);
        } 

四:Form窗体调用

HotKeys.RegHotKey(this.Handle);  //Load或Active事件

HotKeys.UnRegHotKey(this.Handle);//Closing事件

五:Form窗体重写WndPro

       protected override void WndProc(ref Message m)
        {
            const Int32 WM_HOTKEY = 0x0312;
            IntPtr ptr = m.WParam;
            String sptr = ptr.ToString();
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    if (sptr.Equals("555"))
                    {
                        tsb_OK();  //调用事件
                    }
                    else if (sptr.Equals("666"))
                    {
                        barbtn_Referral();
                    }
                    break;
            }
            base.WndProc(ref m);
        }