m_pMainWnd 在 CWinApp 中为 NULL,因为未调用 InitInstance

m_pMainWnd is NULL in CWinApp, because InitInstance is not called

我正在尝试使用 MFC 创建一个简单的 window,但是程序立即终止并且 Debug 的输出行看起来很奇怪:

d:\agent\_work\s\src\vctools\VC7Libs\Ship\ATLMFC\Src\MFC\appcore.cpp(783) : AppMsg - Warning: m_pMainWnd is NULL in CWinApp::Run - quitting application.

进一步检查后,我发现 CMyFrame::InitInstance 没有被调用。我有过一些MFC相关的经验,因为我在Code::Blocks中使用过Win32++(又名Win32xx)。现在我正在使用官方 MFC 框架试用 VS Community 2019,但我无法创建空白 window。这是完整的代码:

//main.cpp
//Code taken from:
//www.tutorialspoint.com/mfc/mfc_windows_fundamentals.htm

#include <afxwin.h>
#include <iostream>

class CMyFrame : public CFrameWnd {
public:
    CMyFrame() {
        Create(NULL, _T("MFC Application Tutorial"));
    }
};

class CExample : public CWinApp {
public:
    CExample() { std::cout << "CExample Constructor\n"; }
    ~CExample() { std::cout << "CExample Destructor\n"; }

    virtual BOOL InitInstance() {
        std::cout << "CExample InitInstance\n";
        CMyFrame* Frame = new CMyFrame();
        m_pMainWnd = Frame; //<--

        Frame->ShowWindow(SW_NORMAL);
        Frame->UpdateWindow();

        return TRUE;
    }
};

CExample theApp;

int main() { return theApp.Run(); }

控制台输出:

CExample Constructor
CExample Destructor

D:\Visual Studio Projects\Visual C++\MFC_Project\Debug\MFC_Project.exe (process 13012) exited with code 0.

尝试在 main 中手动调用 InitInstance 会触发运行时错误。据我所知,InitInstance 应该由 MFC 自动调用。 感谢任何帮助,谢谢:)

这个源代码是哪里来的?它似乎不是由 Visual Studio 自动生成的,因为它没有意义。

MFC 不使用 main() 也不调用 CWinApprun() 方法启动 MFC 应用程序。

请参阅有关 run() 方法的文档,该方法说明它启动消息泵。 https://docs.microsoft.com/en-us/cpp/mfc/reference/cwinapp-class?view=vs-2019#run 这意味着您的应用程序没有执行设置环境所需的任何初始化,因此消息泵实际上可以正确处理消息。

Run acquires and dispatches Windows messages until the application receives a WM_QUIT message. If the application's message queue currently contains no messages, Run calls OnIdle to perform idle-time processing. Incoming messages go to the PreTranslateMessage member function for special processing and then to the Windows function TranslateMessage for standard keyboard translation; finally, the DispatchMessage Windows function is called.

Run is rarely overridden, but you can override it to provide special behavior.

允许 Visual Studio 为 MFC 应用程序生成适当的框架,这将为应用程序创建必要的入口点,link 在所有适当的库中,初始化 MFC 运行时环境,以及启动消息泵以开始处理消息。