C#实现注册全局热键(register hot key)

来源:互联网 发布:淘宝产品经理 编辑:程序博客网 时间:2024/05/01 20:52

想实现注册类似于ctr+alt+shit+A+Z的方法很简单,将RegisterHotKey的第3个参数设置为KeyModifiers.Alt|KeyModifiers.Control|KeyModifiers.Shift,
第4个参数设置为Keys.B|Keys.Z。
 
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.Runtime.InteropServices; 
using System.Threading; 
namespace rgHotKeys 
{ 
    public enum KeyModifiers 
    { 
        None = 0, 
        Alt = 1, 
        Control = 2, 
        Shift = 4, 
        Windows = 8 
    } 
    public partial class Form1 : Form 
    { 
        [DllImport("user32.dll",SetLastError=true)] 
        public static extern bool  RegisterHotKey(IntPtr hwnd,int id,int fsModifiers,int vk); 
        [DllImport("user32.dll", SetLastError = true)] 
        public static extern bool UnregisterHotKey( 
         IntPtr hWnd, // handle to window 
         int id // hot key identifier 
        ); 
        private int id; 
        public Form1() 
        { 
            InitializeComponent(); 
        } 
        private void Form1_Load(object sender, EventArgs e) 
        { 
            id = Thread.CurrentThread.GetHashCode(); 
            RegisterHotKey(this.Handle, id, (int)KeyModifiers.Alt, (int)Keys.F12); 
        } 
        protected override void WndProc(ref Message m) 
        { 
            const int WM_HOTKEY = 0x0312; 
            switch (m.Msg) 
            { 
                case WM_HOTKEY: 
                  if(id==(int)m.WParam) 
                  { 
                            System.Windows.Forms.MessageBox.Show ("你好!");
                    } 
               break; 
            } 
            base.WndProc(ref m); 
        } 
        private void Form1_FormClosed(object sender, FormClosedEventArgs e) 
        { 
            UnregisterHotKey(this.Handle, 10001); 
        } 
    } 
}