Question

Alt + F4 is the shortcut to close a form. When I use this shortcut in an MDI enviroment, the application is closed, so obviously the shortcut applies to the 'Container' and not to the 'Childform'.

What would be the best practice to capture this event and close the active child instead of the container

i read about registering Alt + F4 as hotkey when the MDI activates. When the MDI deactivates, unregistering the hotkey. So,the hotkey doesn't effect other windows.

someone, can tell about registering Alt + F4 or something better

Was it helpful?

Solution

You can change the void Dispose(bool disposing) method in your winform to close your child form instead, like this:

protected override void Dispose(bool disposing)
{
    if (/* you need to close a child form */)
    {
        // close the child form, maybe by calling its Dispose method
    }
    else
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }
}

EDIT: as my commenter said, instead of modifying the overridden Dispose method, you should just override the OnFormClosing method instead, like so:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (/* you need to close the child form */)
    {
        e.Cancel = true;
        // close the child form, maybe with childForm.Close();
    }
    else
        base.OnFormClosing(e);
}

OTHER TIPS

Since no one actually answered the question yet, this can be done by employing the following two steps:

Step 1: Use this straightforward logic to trigger closure of the MDI child form using Alt + F4.

private void child_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Alt && e.KeyCode == Keys.F4) 
    {
        this.Close();
    }
}

Step 2: Also use this hack to disable the Alt + F4 effects impacting the parent MDI form.

private void parent_FormClosing(object sender, FormClosingEventArgs e)
{
    // note the use of logical OR instead of logical AND here
    if (Control.ModifierKeys == Keys.Alt || Control.ModifierKeys == Keys.F4) 
    { 
        e.Cancel = true;
        return;
    }    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top