在 MFC 中显示模态对话框

Display Modal dialogs in MFC

我找不到任何关于 MFC 的好教程,我正在尝试显示一个对话框 window。

我创建了一个新资源,向其中添加了我的控件,它继承自 CDialogEx,但我不知道我应该在哪里放置代码来创建和显示对话框 window,我想要它在应用程序启动时加载,你能给我提示吗?

代码应该在您的应用程序 InitInstance() 中,如下所示:

BOOL MyApp::InitInstance()
{
    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);

    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    CWinApp::InitInstance();

    ExampleDlg dlg; // instance of dialog
    m_pMainWnd = &dlg; // make dialog main window
    INT_PTR nResponse = dlg.DoModal(); // get the response from your modal dialog 
    // this case, OK button, Cancel button or error in dialog
    if (nResponse == IDOK)
    {
        // TODO: Place code here to handle when the dialog is
        //  dismissed with OK
    }
    else if (nResponse == IDCANCEL)
    {
        // TODO: Place code here to handle when the dialog is
        //  dismissed with Cancel
    }
    else if (nResponse == -1)
    {
        TRACE(traceAppMsg, 0, "Warning: dialog creation failed, so application is terminating unexpectedly.\n");
        TRACE(traceAppMsg, 0, "Warning: if you are using MFC controls on the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\n");
    }

这将在您启动应用程序并使其成为主要应用程序时给您一个对话框 window。这可以通过使用 MFC 应用程序向导并选择对话框库轻松完成。它会自动为您提供应用程序的布局。

如果你不想让它成为你的主要 window 只需使用:

ExampleDlg dlg;
dlg.DoModal();

并让您的对话代码完成工作。