开发者

How to implement catching and showing the current key presses using a WPF TextBox?

Like the one in Visual Studio > Options > Keyboard > Press shortcut keys field.

Can I save this key press as a single combined value, or do I have to save the key press 开发者_运维百科and each modifier key separately?

I just wanna show the currently pressed keys in the TextBox like:

Ctrl+G
Alt+X
Shift+V
R
Ctrl+Alt+S
etc

Also looking for the best way to store the keypress value. If I have to store the keys and modifier keys separately, then I will make a new type that has all of them in one place.


In the textbox KeyDown event:

        string keys = "";

        if ((Keyboard.Modifiers & ModifierKeys.Control) > 0)
        {
            keys += "Control + ";
        }

        if ((Keyboard.Modifiers & ModifierKeys.Alt) > 0)
        {
            keys += "Alt + ";
        }

        if ((Keyboard.Modifiers & ModifierKeys.Shift) > 0)
        {
            keys += "Shift + ";
        }

        keys += e.Key;

        YourTextBox.Text = keys;


I'm not aware of any quicker way than what Navid is showing (check for each Modifier individually).

In addition, there is no built-in type that combines the Key and Keyboard.Modifiers already, so you will have to create your own like this:

public class KeyboardStatus
{
    public KeyboardStatus(Key key, ModifierKeys modifiers)
    {
        _modifiers = modifiers;
    }

    public Key PressedKey { get; set; }
    public bool IsControlPressed { get { return ((_modifiers & ModifierKeys.Control) > 0); } }
    // ....

    public override string ToString()
    {
        string display = string.Empty;

        display += ((Keyboard.Modifiers & ModifierKeys.Control) > 0) ? "Ctrl + " : string.Empty;
        display += ((Keyboard.Modifiers & ModifierKeys.Alt) > 0) ? "Alt + " : string.Empty;
        display += ((Keyboard.Modifiers & ModifierKeys.Shift) > 0) ? "Shift + " : string.Empty;
        display += ((Keyboard.Modifiers & ModifierKeys.Windows) > 0) ? "Win + " : string.Empty;
        display += PressedKey.ToString();
        return display;
    }
    ModifierKeys _modifiers;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜