Click here to Skip to main content
15,924,036 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
I am attempting to catch a keyup event. For some reason using the regular KeyUp event handler is not working in C#. What I am wanting to do is run some code when the Alt key is lifted. I tried using this:
protected override void OnKeyUp(KeyEventArgs e)<br />
{<br />
    base.OnKeyUp(e);<br />
}<br />

and placed a break point on the line of base.OnKeyUp(e) and no matter what was pressed the debugger wouldn't stop there. I have also attempted using an override for about every key event I could find. The only one that had any success was ProcessDialogKey but the only information it gave under keyData was RButton | Shiftkey | Alt which gives no indication whether it was a KeyDown or KeyUp, and I'm not even sure it would work for KeyUp. Any suggestions?

I did further testing on ProcessDialogKey with this:
int x = 0;<br />
protected override bool ProcessDialogKey(Keys keyData)<br />
{<br />
    if (keyData.ToString().Contains("Alt") == true && x == 0)<br />
        x += 1;<br />
    else<br />
x = 2;<br />
    return base.ProcessDialogKey(keyData);<br />
}<br />

and placed the break point on the line of x = 2 to attempt to see if this worked for KeyUp and KeyDown. The debugger did not stop at this line for the KeyUp event but did stop the second time I pushed the Alt key.
Posted
Updated 3-Dec-10 16:44pm
v2

Have you tried to add myForm.KeyPreview = true;
 
Share this answer
 
Comments
LordXandor 4-Dec-10 17:05pm    
This worked perfectly. I was unaware of this property, nor did I think that if a control inside my form had focus that the event handler for my form wouldn't receive the event. This was greatly appreciated.
Toli Cuturicu 4-Dec-10 17:08pm    
Thank you. Anyway, I must say that Abhinav told you the same thing, but not so directly.
LordXandor 4-Dec-10 21:36pm    
Yes, actually I had noticed that, but my first thought was to add an event handler to each control, which realistically would not be that many, this particular form doesn't have many. But this property made it so much easier, either way. Both responses were appreciated.
Since Alt is used for some system related things, it sometimes gives problems and has to be handled somewhat differently than normal keys. See here[^]
 
Share this answer
 
Comments
Abhinav S 3-Dec-10 23:24pm    
Nice answer.
Check if the key event appears to be getting routed to another control.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900