views:

361

answers:

2

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.

A: 

You could remove the modifier flags :

pressed += (e.KeyCode & ~Keys.Modifiers & ~Keys.ShiftKey  & ~Keys.ControlKey);
Thomas Levesque
Unfortunately, that doesn't seem to stop it from returning the modifier key itself. Thanks, though.
GeminiDomino
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
No, I didn't change anything...
Thomas Levesque
Why the down-vote ?
Thomas Levesque
+1  A: 

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
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
For *elegant ways* take a look at http://stackoverflow.com/questions/921180/c-round-up/926806#926806
Oliver