views:

1070

answers:

2

I need to capture the KeyUp event in my form (to toggle a "full screen mode"). Here's what I'm doing:

protected override void OnKeyUp(KeyEventArgs e)
{
    base.OnKeyUp(e);

    if (e.KeyCode == Keys.F12) this.ToggleFullScreen();
}

private void ToggleFullScreen()
{
    // Snazzy code goes here           
}

This works fine, unless a control on the form has focus. In that case, I don't get the event at all (also tried OnKeyDown - no luck there either).

I could handle the KeyUp event from the child control, but the controls on the form are generated dynamically, and there may be many of them - each having many children of their own.

Is there any way to do this without generating event handlers for every control on the screen (which I certainly could do with a recursive function)?

+2  A: 

Have you tried handling the events globally on your form?

protected override bool ProcessCmdKey(ref Message msg, Keys e)
{
    if (e.KeyCode == Keys.F12) 
    {
       this.ToggleFullScreen();
       return true; //marks command as handled
    }

    return base.ProcessCmdKey(ref msg, e); // Resend To Base Function
}
Joseph
This does work too, thanks.
Jon B
+5  A: 

Set the form's KeyPreview to true and you can intercept the KeyUp event.

In my test app I did something like this:

this.KeyPreview = true;
.
.
.


private void button1_KeyUp(object sender, KeyEventArgs e)
{
    Trace.WriteLine("button key up");
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    Trace.WriteLine("form key up");
    e.Handled = true;
}

It'll dump the form trace line, handle the key up and the button handler won't get called. You could, of course, not handle the event (not do the e.Handled = true) and then the button handler would get called too.

itsmatt
Short and sweet. I like it!
Joseph
Just what I needed! Perfect Thanks!
Lee Warner