简体   繁体   English

创建一个控件以捕获使用定义的按键组合

[英]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.) 例如,我当前有一个文本框,如果用户有焦点然后按下某个键,它将记录并显示该文本框内所按下的键,我的问题是涉及组合键或特殊键(CTRL, ALT,BACKSPACE等)

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. 目前,它的行为非常奇怪,如果我按“ CTRL + O”,它将在文本框中显示“ CTRL +”。 Even if I press BACKSPACE it just prints CTRL anyway. 即使我按BACKSPACE,它仍然会打印CTRL。

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. 作为一种选择,您可以基于TextBox创建一个TextBox并将其设置为只读,然后重写某些键函数(如ProcessCmdKey ,然后使用KeysConverter类将按下的键转换为字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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