I'm writing an MFC multiple document (MDI) application. In the parent window, how do I check that all MDI child windows are turned off? If all is turned off, then I want to activate a pane in my main window.
Ramesh
Windows and MFC do not provide any specialized functions to get the number of MDI child windows, but it is easy to achieve the functionality you want. In fact, I can think of half a dozen ways to solve this problem. You can capture Wm_create/wm_destroy messages, you can install Windows hooks with SetWindowsHookEx, you can use EnumWindows to enumerate child windows, and calculate the number of them. But the simplest solution is often the easiest way to be overlooked.
The problem is simply that the application uses the MDI interface or any other Windows user interface that you have designed--in the final analysis, a list of Windows. Figure 1 shows a class based on the Standard Template Library (STL) list, and it's hard to say if it's worth it, but I just think it's amazing that Windows programmers type "Push_back" in their code. Cwinlist makes you use "ADD" instead. To use cwinlist, you only need to add a global instance somewhere, either as a global variable or as a data member in the main application class:
class CMyApp : public CWinApp {
public:
CWinList m_winlist; // 打开的恶窗口列表
};
To track child windows, you only need to add or remove this list when you create or destroy child windows. Obviously the best place to do this is in the constructor and destructor of the proposed tracing window:
CMyView::CMyView()
{
theApp.m_winlist.Add(this);
}
CMyView::~CMyView()
{
theApp.m_winlist.Remove(this);
}
In addition, you can call Add and Remove from the OnCreate and OnDestroy handler functions to ensure that your list contains a valid HWNDs window object. Because the cwinlist is derived from the list<cwnd*>, so the process can be fully aided by the power of STL. For example, you can enumerate the windows in the list using the iterator (iterator) of the STL list:
CWinList& wl = theApp.m_winlist;
for (CWinList::iterator it=wl.begin(); it!=wl.end(); it++) {
CWnd* pWnd = *it;
// do something
}
I wrote a small program wincount, which uses cwinlist to Count MDI child windows. Run the screen as shown in Figure 2.
Figure 2 Compute the wincount of the child window
Wincount A Status bar pane displays the number of open windows in the bottom right corner, and the About dialog box for the program lists the window's caption. The "About" dialog box is a feedback message that uses cwinlist::iterator to produce it; The Status bar pane is a standard MFC indicator pane that uses ON_UPDATE_COMMAND_UI to display the number of views.
void CMainFrame::OnUpdateWinIndicator(CCmdUI* pCmdUI)
{
CString s;
s.Format(_T("Open:%d"), theApp.m_winlist.size());
pCmdUI->SetText(s);
}