简体   繁体   中英

Configurable global keyboard hotkeys

im looking for a way to allow the user to configure the global hotkey for my application. At the moment I use this code to register global hotkeys: http://yuu.li/z4Qv9K

My problem is, how to allow the user to customize the hotkey at runtime? I thought about, pressing a windows forms button and then pressing the hotkey you want to set. But i would need to register all keys on every keyboard to recognize the keys the user is pressing.

Hope you understand what I mean, thank you :D

Windows has a built-in control for this. Creating a little .NET wrapper class for such controls is pretty easy to do. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. Note that you can set the Hotkey property in the designer. You just need to add an OK button to let the user change his preferred choice. Saving it in an application setting for example.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM