C #: How do you display the modifier key name + key name without modifier in this keydown event?

I use this code to determine if modifier keys are held in the KeyDown event of a text field.

    private void txtShortcut_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Shift || e.Control || e.Alt)
        {
            txtShortcut.Text = (e.Shift.ToString() + e.Control.ToString() + e.Alt.ToString() + e.KeyCode.ToString());

        }
    }

How can I display the actual modifier key name and not the bool result, and also display the non-modifier key pressed at the end of the modifier key if the non-modifier key, such as the letter A, is pressed at the same time too? Is there a way to do all this in the same txtShortcut.Text = (); line?

+2
source share
4 answers

You can check Control.ModifierKeys- because it is an enumeration that should be more human friendly. Alternatively just

string s = (e.Shift ? "[Shift]+" : "") + (e.Control ? "[Ctrl]+" : "")
           + (e.Alt ? "[Alt]+" : "") + e.KeyCode;
+2
source

?: Operator

txtShortcut.Text = (e.Shift? "Shift ": "") + (e.Control? "Control ": "") + (e.Alt? "Alt ": "")  + e.KeyCode.ToString());
+1

bool. - , ?: :

txtShortcut.Text = (e.Shift ? "[Shift]" : string.Empty) + 
                   (e.Control ? "[Ctrl]" : string.Empty) + ...;

, :

<someBool> ? <ifTrue> : <ifFalse>

.

0

.NET 3, KeysConverter, -:

var kc = new KeysConverter();
var result = kc.ConvertToString(e.KeyCode);

:

var keys = (e.Shift ? "[Shift]+" : string.Empty)
             + (e.Control ? "[Ctrl]+" : string.Empty)
             + (e.Alt ? "[Alt]+" : string.Empty)
             + e.KeyCode;
0

Source: https://habr.com/ru/post/1727228/


All Articles