[最后的留存]
MFC对话框程序改为无模式对话框
白云小飞
第一、通过VC应用程序向导生成一个MFC模式对话框程序框架
第二、在CMyApp中增加一个CDialog*类型(当然也可以是CMyDialog*)的指针变量m_pMainDlg。
//my.h
class CMyApp : public CWinApp
{
public:
……
CDialog * m_pMainDlg;
};
第三、在CMyApp::InitInstance()中修改代码如下:
//my.cpp
BOOL CMyApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
m_pMainDlg = new CMyDlg;
m_pMainWnd = m_pMainDlg; //必须赋值给m_pMainWnd
m_pMainDlg->Create(IDD_MY_DIALOG);
m_pMainDlg->ShowWindow(SW_NORMAL);
return TRUE; //注意这里返回TRUE
/*以下注释
CMyDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
……
return FALSE;
*/
}
第四、在CMyApp中重写虚函数ExitInstance(),并添加代码如下:
//my.cpp
int CMyApp::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
M_pMainWnd = NULL;
m_pMainDlg->DestroyWindow();
delete m_pMainDlg ;
return CWinApp::ExitInstance();
}
第五、在CMyDlg类是重写虚函数OnCance()及OnOK(),并添加代码如下:
void CMyDlg::OnCancel()
{
// TODO: Add extra cleanup here
PostQuitMessage(0); //目的是为了在关闭主窗口时退出消息循环
CDialog::OnCancel();
}
第六、程序在哪里进行消息循环呢?
在MFC类库中CWinThread里的虚函数Run()中,而CWinApp是派生自CWinThread。现复制出其代码片断:
int CWinThread::Run()
{
……
do
{
// pump message, but quit on WM_QUIT
if (!PumpMessage())
return ExitInstance();
// reset "no idle" state after pumping "normal" message
if (IsIdleMessage(&m_msgCur))
{
bIdle = TRUE;
lIdleCount = 0;
}
}while(::PeekMessage(&m_msgCur, NULL, NULL, NULL, PM_NOREMOVE));
……
}
程序在此处不断循环,获取消息并发送到各消息处理对象(如窗口类对象)
有错吗?