开发者

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开发者_如何学Go)
{
    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.


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


You could remove the modifier flags :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜