简体   繁体   中英

Creating a control to capture use defined key combinations

I want to create a small control that allows the users of my application to define key combinations, and display them in a human readable format.

For example, I currently have a text box and if the user has focus and then presses a key, it will record and display the pressed key within the text box, my issues are when it comes to key combinations, or special keys (CTRL, ALT, BACKSPACE etc.)

Here is the simple code I have at the moment, which I was using just to experiment:

    private void tboxKeyCombo_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (tboxKeyCombo.Focused)
        {
            string sKeyboardCombo = String.Empty;

            if (char.IsLetterOrDigit(e.KeyChar))
            {
                sKeyboardCombo += e.KeyChar.ToString();
            }
            else if (char.IsControl(e.KeyChar))
            {
                sKeyboardCombo += "CTRL";
            }

            tboxKeyCombo.Text += sKeyboardCombo + "+";
        }
    }

At the moment it behaves very weirdly, if I was to press "CTRL+O" it would display "CTRL+" in the text box. Even if I press BACKSPACE it just prints CTRL anyway.

I think I'm misunderstanding some of the parts of deciphering the keyboard input, so any help would be brilliant - thank you.

As an option, you can create a control based on TextBox and make it read-only, then override some key functions like ProcessCmdKey and convert pressed keys to string using KeysConverter class.

Example

using System.Windows.Forms;
public class MyTextBox : TextBox
{
    public MyTextBox() { this.ReadOnly = true; }
    public Keys ShortcutKey { get; set; }
    public new bool ReadOnly
    {
        get { return true; }
        set { base.ReadOnly = true; }
    }
    KeysConverter converter = new KeysConverter();
    protected override bool ProcessCmdKey(ref Message m, Keys keyData)
    {
        ShortcutKey = keyData;
        this.Text = converter.ConvertToString(keyData);
        return false;
    }
}

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