简体   繁体   中英

How to properly prompt the user when closing an MDI form and children?

I'm writing an IRC client, where there is an MDI parent with Server and Channel windows. When you close a Server window, it prompts the user and if they want to close it, the connection to the server is closed etc.

I would like there to be only one prompt when the MDI parent is closed rather than a prompt for each server. The problem is when the user tries to close the parent, the child Forms' OnFormClosing is called before the parent's.

Another option is to catch the MDI "close" BEFORE the child windows using the MDI's DefWndProc and "kill" the child windows there.

''' <remarks>Intercept the user clicking on the CLOSE button (or ALT+F4'ing) before the closing starts.</remarks>
Protected Overrides Sub DefWndProc(ByRef m As System.Windows.Forms.Message)

    Try
        Const SC_CLOSE = &HF060 'http://msdn.microsoft.com/en-us/library/ms646360%28v=vs.85%29.aspx

        If (m.Msg = WndMsg.WM_SYSCOMMAND) _
        AndAlso (m.WParam.ToInt32 = SC_CLOSE) Then

            If (Not Me.ExitApplicationPrompt()) Then ' Do your "close child forms" here
                m.Msg = 0 'Cancel the CLOSE command
            End If

        End If

    Catch ex As Exception
        My.ExceptionHandler.HandleClientError(ex)
    End Try

    MyBase.DefWndProc(m)

End Sub

Modify the MDI child form's FormClosing event to the following:

private void MyChildForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.MdiFormClosing)
    {
        e.Cancel = true;
        return;
    }

    // Child window closing code goes here
}

And then put your global closing prompt/logic in the MDI parent form's FormClosing event. Hint: use this.MdiChildren in combination with window type tests, ie, childForm is IServerForm .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM