views:

354

answers:

2

Hi,

I have a control with KeyDown and KeyUp events as shown below. The problem I am having is that 'x' is TRUE in KeyDown but always FALSE in KeyUp. I am trying to detect the Alt key (as you may have guessed).

Is there a gottcha that I don't know. I mean, when I press Alt it detects it ok but on keyup it's false.

Any suggestions/ideas

Thanks

    private void MyControl_KeyDown(object sender, KeyEventArgs e)
    {
        bool x;
        x = ((int) (e.KeyData & Keys.Alt) != 0);
        x = (e.KeyData & Keys.Alt) == Keys.Alt;
        x = e.Alt;
    }
    private void MyControl_KeyUp(object sender, KeyEventArgs e)
    {
        bool x;
        x = ((int) (e.KeyData & Keys.Alt) != 0);
        x = (e.KeyData & Keys.Alt) == Keys.Alt;
        x = e.Alt;
    }
+2  A: 

Are you trying to detect an Alt+[letter] event? Is so, try this:

        private void YourControl_KeyDown(object sender, KeyEventArgs e)
        {
          if((e.Alt) & (e.KeyCode  == Keys.X))
          {
            MessageBox.Show("Alt-X pressed");
          }
        }

For just Alt, try this:

    private void YourControl_KeyDown(object sender, KeyEventArgs e)
    { 
        if (e.KeyCode  == Keys.Menu)
        {
            //YourCode
            e.Handled = true;
        }
    }

    private void YourControl_KeyUp(object sender, KeyEventArgs e)
    { 
        if (e.KeyData == Keys.Menu)
        {
            //YourCode
            e.Handled = true;
        }
    }
bluecoder
No, I am just trying to detect the Alt key that's all, no combination.
ofarooq
I've added code for just Alt in my answer above. Because Alt serves the purpose of displaying menus, you have to do a e.Handled=true unless you only want to catch 50% of the Alt presses. The check for KeyUp is slightly different than KeyDown (see above). Does that work for you?
bluecoder
Thanks that did work.
ofarooq
A: 

I hope you're not just setting a bool member variable in your class in response to the Alt key being pressed.

If you want to know if the Alt key is down while executing code in response to other events (eg mouse events) use the Control.ModifierKeys property as it is far more reliable. It also means you don't have a redundant member variable.

If you are actually trying to detect if the user has pressed just a Modifier key by itself then @bluecoder's solution is probably what you want.

orj