Creating a control to capture use defined key combinations

折月煮酒 提交于 2019-12-11 16:09:56

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/49916896/creating-a-control-to-capture-use-defined-key-combinations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!