2

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, KeyEventArgs e)
    {
        if (e.Shift || e.Control || e.Alt)
        {
            txtShortcut.Text = (e.Shift.ToString() + e.Control.ToString() + e.Alt.ToString() + e.KeyCode.ToString());

        }
    }

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

  • Duplicate: http://stackoverflow.com/questions/676518/c-in-the-keydown-event-of-a-textbox-how-do-you-detect-currently-pressed-modifi – Program.X Mar 24 '09 at 08:40
  • its a follow up question, not a duplicate. He's using the answer from the previous question in this one – RvdK Mar 24 '09 at 08:41

4 Answers4

2

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;
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

use the ?: Operator

txtShortcut.Text = (e.Shift? "Shift ": "") + (e.Control? "Control ": "") + (e.Alt? "Alt ": "")  + e.KeyCode.ToString());
RvdK
  • 19,580
  • 4
  • 64
  • 107
0

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.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
0

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;
John Feminella
  • 303,634
  • 46
  • 339
  • 357