可配置的全局键盘热键

本文关键字:键盘 全局 配置 | 更新日期: 2023-09-27 18:33:30

im 正在寻找一种方法来允许用户为我的应用程序配置全局热键。目前我使用此代码注册全局热键:http://yuu.li/z4Qv9K

我的问题是,如何允许用户在运行时自定义热键?我想了想,按下Windows表单按钮,然后按要设置的热键。但是我需要注册每个键盘上的所有键才能识别用户正在按下的键。

希望你明白我的意思,谢谢:D

可配置的全局键盘热键

Windows对此有一个内置控件。 为此类控件创建一个小的 .NET 包装类非常容易。 向项目添加新类并粘贴如下所示的代码。 编译。 将新控件从工具箱顶部拖放到窗体上。 请注意,您可以在设计器中设置热键属性。 您只需要添加一个"确定"按钮,让用户更改其首选选项。 例如,将其保存在应用程序设置中。

using System;
using System.Drawing;
using System.Windows.Forms;
public class HotKeyControl : Control {
    public HotKeyControl() {
        this.SetStyle(ControlStyles.UserPaint, false);
        this.SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, false);
        this.BackColor = Color.FromKnownColor(KnownColor.Window);
    }
    public Keys HotKey {
        get {
            if (this.IsHandleCreated) {
                var key = (uint)SendMessage(this.Handle, 0x402, IntPtr.Zero, IntPtr.Zero);
                hotKey = (Keys)(key & 0xff);
                if ((key & 0x100) != 0) hotKey |= Keys.Shift;
                if ((key & 0x200) != 0) hotKey |= Keys.Control;
                if ((key & 0x400) != 0) hotKey |= Keys.Alt;
            }
            return hotKey;
        }
        set { 
            hotKey = value;
            if (this.IsHandleCreated) {
                var key = (int)hotKey & 0xff;
                if ((hotKey & Keys.Shift)   != 0) key |= 0x100;
                if ((hotKey & Keys.Control) != 0) key |= 0x200;
                if ((hotKey & Keys.Alt)     != 0) key |= 0x400;
                SendMessage(this.Handle, 0x401, (IntPtr)key, IntPtr.Zero);
            }
        }
    }
    protected override void OnHandleCreated(EventArgs e) {
        base.OnHandleCreated(e);
        HotKey = hotKey;
    }
    protected override CreateParams CreateParams {
        get {
            var cp = base.CreateParams;
            cp.ClassName = "msctls_hotkey32";
            return cp;
        }
    }
    private Keys hotKey;
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}