3

I'm trying to accomplish something similar to the fellow here, but going with the answer there leaves me with a bit of a bug that's not a huge deal, but ugly from a user POV:

When it puts the keypress data into the textbox, if the user presses the modifier keys before the character (like one does), the textbox is being populated including the keyname of the modifier. I.e., I'm getting results like "CTRL + SHIFT + ShiftKey". Anything I try to do to suppress that last keycode ends up suppressing the real keys as well.

This is my base attempt (forgive the blockiness, I've been breaking it down and rewriting bits of it trying to work this out on my own, to no avail) without the suppression I'm asking for.

String pressed ="";
e.SuppressKeyPress = true;
if ((e.Modifiers & Keys.Control) > 0)
{
    pressed += "CTRL + ";
}
if ((e.Modifiers & Keys.Alt) > 0)
{
    pressed += "ALT + ";
}
if ((e.Modifiers & Keys.Shift) > 0)
{
    pressed += "SHIFT + ";
}


    pressed += e.KeyCode; 


    txtCopyKey.Text = pressed;

Hopefully I'm clear enough here on what I'm asking.

Community
  • 1
  • 1
GeminiDomino
  • 451
  • 1
  • 5
  • 19
  • 4
    You'll probably get away with it, but *strictly* you should use `!=0` here, not `>0`, as if the MSB is set it will appear as negative. – Marc Gravell Jan 04 '10 at 12:44

2 Answers2

3

What about this solution:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    StringBuilder sb = new StringBuilder();

    if (e.Control)
    {
        sb.Append(Keys.Control.ToString());
        sb.Append(" + ");
    }

    if (e.Alt)
    {
        sb.Append(Keys.Alt.ToString());
        sb.Append(" + ");
    }

    if (e.Shift)
    {
        sb.Append(Keys.Shift.ToString());
        sb.Append(" + ");
    }

    if (e.KeyCode != Keys.ShiftKey
        && e.KeyCode != Keys.ControlKey
        && e.KeyCode != Keys.Menu)
    {
        sb.Append(e.KeyCode.ToString());
    }

    textBox1.Text = sb.ToString();
}
Oliver
  • 43,366
  • 8
  • 94
  • 151
  • That did occur to me. I wanted to make sure I wasn't missing a more elegant way to do it though. I'll test it out shortly, thanks. – GeminiDomino Jan 04 '10 at 15:29
  • For *elegant ways* take a look at http://stackoverflow.com/questions/921180/c-round-up/926806#926806 – Oliver Jan 05 '10 at 08:16
1

You could remove the modifier flags :

pressed += (e.KeyCode & ~Keys.Modifiers & ~Keys.ShiftKey  & ~Keys.ControlKey);
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Unfortunately, that doesn't seem to stop it from returning the modifier key itself. Thanks, though. – GeminiDomino Jan 04 '10 at 13:14
  • Did you change it? Now it sort of works, handling the modifier-only key situation correctly, but it ends up with the wrong key when the character key is finally pressed (i.e. Ctrl-X results in "CTRL + H" and Ctrl-C gives "CTRL + 64" – GeminiDomino Jan 04 '10 at 17:16