GeminiDomino
GeminiDomino

Reputation: 451

C# (VS2008) Suppressing Keycode for modifier keys, but keeping modifiers

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.

Upvotes: 3

Views: 1558

Answers (2)

Oliver
Oliver

Reputation: 45109

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();
}

Upvotes: 3

Thomas Levesque
Thomas Levesque

Reputation: 292545

You could remove the modifier flags :

pressed += (e.KeyCode & ~Keys.Modifiers & ~Keys.ShiftKey  & ~Keys.ControlKey);

Upvotes: 1

Related Questions