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

前端 未结 4 1077
攒了一身酷
攒了一身酷 2021-01-21 22:01

I am using this code to detect whether modifier keys are being held down in the KeyDown event of a text box.

    private void txtShortcut_KeyDown(object sender,          


        
相关标签:
4条回答
  • 2021-01-21 22:18

    use the ?: Operator

    txtShortcut.Text = (e.Shift? "Shift ": "") + (e.Control? "Control ": "") + (e.Alt? "Alt ": "")  + e.KeyCode.ToString());
    
    0 讨论(0)
  • 2021-01-21 22:34

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

    string s = (e.Shift ? "[Shift]+" : "") + (e.Control ? "[Ctrl]+" : "")
               + (e.Alt ? "[Alt]+" : "") + e.KeyCode;
    
    0 讨论(0)
  • 2021-01-21 22:34

    If you are using .NET 3, you will want to use the KeysConverter class, which has support for localized names of the modifier keys:

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

    Otherwise, you can do it yourself with the ternary operator:

    var keys = (e.Shift ? "[Shift]+" : string.Empty)
                 + (e.Control ? "[Ctrl]+" : string.Empty)
                 + (e.Alt ? "[Alt]+" : string.Empty)
                 + e.KeyCode;
    
    0 讨论(0)
  • 2021-01-21 22:38

    You need to display the right string depending on the bool value. To do things like that in a single statement, use the ? : operator:

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

    Generally, it's:

    <someBool> ? <ifTrue> : <ifFalse>
    

    It works with any type.

    0 讨论(0)
提交回复
热议问题