设置全局快捷键

public partial class Form1 : Form
{
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool RegisterHotKey(
        IntPtr hWnd,                //要定义热键的窗口的句柄
        int id,                     //定义热键ID(不能与其它ID重复)           
        int fsModifiers,            //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效
        int vk                      //定义热键的内容
        );
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(
        IntPtr hWnd,                //要取消热键的窗口的句柄
        int id                      //要取消热键的ID
        );

    enum KeyModifier // 按键枚举值
    {
        None = 0,
        Alt = 1,
        Control = 2,
        Shift = 4,
        WinKey = 8
    }
    public Form1()
    {
        InitializeComponent();
        // 注册快捷键Shift+S, 设置id为1
        RegisterHotKey(this.Handle, 1, (int)KeyModifier.Shift, Keys.S.GetHashCode());
        // 注册快捷键Shift+A, 设置id为2
        RegisterHotKey(this.Handle, 2, (int)KeyModifier.Shift, Keys.A.GetHashCode());
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == 0x0312) // 如果m.Msg的值为0x0312那么表示用户按下了热键
        {
            int id = m.WParam.ToInt32();

            if (id == 1)
            {
                MessageBox.Show("1");
            }
            else if (id == 2)
            {
                MessageBox.Show("2");
            }
        }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        UnregisterHotKey(Handle, 1); //卸载第1个快捷键
        UnregisterHotKey(Handle, 2); //缷载第2个快捷键
    }
}

转载于:https://www.cnblogs.com/jizhiqiliao/p/10135306.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值