Closing MDI Child Window Via Button on CFormView Derived Class

Closing MDI Child Window Via Button on CFormView Derived Class

I’m writing an MDI application that has two documents. One of the documents has multiple views, which are implemented as FormViews. Several views for the same document can be open at the same time. I need to be able to close a view with a button. This leaves the document and any other views open. Both close from the system menu and work fine using the ‘X’ to close. I want the same functionality, but in a button on the form.

From within the trigger for the button, I’ve tried to execute the system menu close with the following:

This has no effect. I’ve also tried to call DestroyWindow() and OnClose() from the same trigger. OnClose() does nothing, and DestroyWindow() affects the window so it is not redrawn, but is still visible.

Any ideas?

You’re on the right track. However, you must post the message to the child frame window that contains the view. The following code will close a child window as a result of the user pressing a button.

With the assistance of ClassWizard, add a message map macro and message map function for a specified button’s click event to the CFormView derived class similar to the code extract below.

// CMyFormView.cpp…BEGIN_MESSAGE_MAP(CMyFormView, CFormView)        //{{AFX_MSG_MAP(CMyFormView)        ON_BN_CLICKED(IDC_BUTTON1, OnButton1)        //}}AFX_MSG_MAPEND_MESSAGE_MAP()…void CMyFormView::OnButton1() {        // Get parent, which should be the the child frame window in this case.        CWnd* pParentWnd = GetParent();                // Post the SC_CLOSE message to the child frame window.  This will eventually        // lead to the Window and its child controls being destroyed.        if (pParentWnd)                pParentWnd->PostMessage(WM_SYSCOMMAND, SC_CLOSE);        } 
Notice I call CWnd::GetParent() to acquire the parent window of CMyFormView which is a CWnd pointer. Then I call CWnd::PostMessage(?) on this window, causing the MDI child window to close properly.

See also - an AI reverse image search platform

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist