Sign in to follow this  
ofarooq

C#: : Problems Detecting Alt Key on the Control.KeyUp event

Recommended Posts

ofarooq    122
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 GraphEditor_KeyUp(object sender, KeyEventArgs e) { bool x; x = ((int) (e.KeyData & Keys.Alt) != 0); x = (e.KeyData & Keys.Alt) == Keys.Alt; x = e.Alt; }

Share this post


Link to post
Share on other sites
BLiTZWiNG    361
That is wierd... I notice that KeyCode is RButton | ShiftKey (KeyCode 18) rather than Alt. But if you hold alt and press then release a key, say T, then Alt is true and key code is 73. It seems to only not detect the lifting of the Alt key itself.

Yet, if you go to the definition of Keys enum, 18 is called Menu, and in the comment is labelled as Alt.

Share this post


Link to post
Share on other sites
benryves    1999
Note that it's the same for Control (ControlKey) and Shift (ShiftKey). I suspect the lack of an AltKey is that Alt has a prescribed purpose (activate the menu) whereas Control and Shift don't have that luxury.

Share this post


Link to post
Share on other sites
BLiTZWiNG    361
Quote:
Original post by benryves
Note that it's the same for Control (ControlKey) and Shift (ShiftKey). I suspect the lack of an AltKey is that Alt has a prescribed purpose (activate the menu) whereas Control and Shift don't have that luxury.


That's the feeling I have too. I'd have preferred consistency though.

Share this post


Link to post
Share on other sites
arbitus    440
Edited for clarity:

The "Alt" key activates the menu bar when the key is released. This is handled by the ProcessCmdKey() method, and it stops the KeyUp event from occurring for the Alt key. Instead, you get a Menu key event, or you can detect Alt as a modifier on another key event.

I tend to override the ProcessCmdKey() method to just pass on the Alt key events so that it does not try and activate menus (when I am not using a GUI with a menu). In addition, you need the help of GetAsyncKeyState() if you want to detect which alt, ctrl, or shift key is pressed.

[Edited by - arbitus on February 9, 2010 8:27:43 PM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this