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

I am trying to do something similar with someone here , but coming out of the answer, I leave me a little error, which is not a huge deal, but ugly from the POV user:

When he puts the keypress data in a text field, if the user presses the modifier keys before the character (like one), the text field is filled, including the name of the modifier key. Ie, I get the results as "CTRL + SHIFT + ShiftKey". Everything I try to suppress this last keycode also suppresses real keys.

This is my main attempt (to forgive blockiness, I broke it and rewrote it, trying to figure it out on my own, to no avail) without the suppression that I ask 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;

Hope I'm clear enough here what I'm asking.

+3
source share
2 answers

How 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();
}
+3
source

You can remove modifier flags:

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

Source: https://habr.com/ru/post/1727225/


All Articles