【问题标题】:MFC dialog based application fails to invoke dialog twice基于 MFC 对话框的应用程序无法两次调用对话框
【发布时间】:2019-08-30 14:24:06
【问题描述】:

我有一个基于 MFC 对话框的应用程序,我想在其中更改对话框。为此,我关闭对话框并尝试使用另一个对话框模板再次加载它。对话框的第二次调用失败,返回码为 -1。

即使不更改模板,问题仍然存在。 GetLastError() 返回 0。我使用 AppWizard 生成了最简单的示例。

App 向导在 CMyApp::InitInstance 中生成以下代码:

CMyAppDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
    ...

这个我改成了:

CMyAppDlg *pdlg = new CMyAppDlg;
m_pMainWnd = pdlg;
INT_PTR nResponse = pdlg->DoModal();
if (nResponse == IDOK)
{}
delete pdlg;

CMyAppDlg dlg1;
m_pMainWnd = &dlg1; // leaving this out makes no difference
nResponse = dlg1.DoModal();// this exits immediately with a -1
if (nResponse == IDOK)

...

第一个 DoModal() 工作正常。当我按 OK 或 Cancel 时,第二个 DoModal() 无法返回 -1。

【问题讨论】:

  • "对话框的第二次调用失败,返回码为 -1。" 在看到这样的返回值后,您是否尝试查看 GetLastError 返回的内容,如在documentation?中描述?
  • @alg:您不能在 MFC 应用程序中调用 GetLastError。请再次阅读文档。
  • @IInspectable 请提供报价,说明不能在 MFC 应用程序中调用 GetLastError
  • 如果DoModal 返回IDABORTCDialog::DoModal 的文档说GetLastError 会提供更多信息。否则GetLastError 没有用处。在这种情况下GetLastError 为 0,因为没有 Windows 错误,这是一个 MFC 问题。
  • @bar:文档没有这么说。

标签: c++ mfc dialog


【解决方案1】:

来自m_pMainWnd的文档

Microsoft 基础类库将自动终止 当 m_pMainWnd 引用的窗口关闭时,您的线程。如果 此线程是应用程序的主线程,应用程序 也将被终止。如果此数据成员为 NULL,则主窗口 对于应用程序的 CWinApp 对象,将用于确定何时 终止线程。 m_pMainWnd 是 CWnd* 类型的公共变量。

所以当主窗口关闭时,MFC 已经决定应用程序结束,不会创建额外的窗口。

最小可重现代码:

BOOL CMyWinApp::InitInstance()
{
    CWinApp::InitInstance();

    CDialog *pdlg = new CDialog(IDD_DIALOG1);
    m_pMainWnd = pdlg; //<- remove this to see the message box
    pdlg->DoModal();
    m_pMainWnd = NULL; //<- this line has no effect basically
    delete pdlg;

    MessageBox(0, L"You won't see this message box", 0, 0);
    TRACE("but you will see this debug line\n");

    return FALSE;
}

要修复它,您可以删除行 //m_pMainWnd = pdlg; 并让 MFC 处理它。

更好的是,更改程序设计,使 GUI 线程始终只有一个主窗口。

【讨论】:

  • 删除行 m_pMainWnd = pdlg;解决了这个问题。谢谢巴马克!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2011-07-03
  • 1970-01-01
相关资源
最近更新 更多