[学习]MFC对话框程序改为无模式对话框

本文详细介绍了如何将MFC应用程序中的模式对话框转换为无模式对话框,包括在CMyApp类中添加对话框指针、修改InitInstance()函数、重写ExitInstance()函数以及CMyDlg类中的OnCancel()和OnOK()函数,最终实现无模式对话框的显示和关闭机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[最后的留存]

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));

       ……

}

程序在此处不断循环,获取消息并发送到各消息处理对象(如窗口类对象)

 

 

有错吗?

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值