Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture KeyUp event on form when child control has focus

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)?

like image 850
Jon B Avatar asked Jun 19 '09 14:06

Jon B


2 Answers

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.

like image 154
itsmatt Avatar answered Nov 20 '22 05:11

itsmatt


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
}
like image 30
Joseph Avatar answered Nov 20 '22 03:11

Joseph