如何从头开始启动MFC应用程序?

时间:2011-08-19 16:02:11

标签: c++ mfc

换句话说,来自空白的win32项目(没有向导)。

这就是我所在的地方:

预处理器定义:WIN32

Linker-> System-> Subsystem = Console

int _tmain()
{
    int nRetCode = 0;

    // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
        // TODO: change error code to suit your needs
        _tprintf(_T("Fatal Error: MFC initialization failed\n"));
        return nRetCode = 1;
    }

    MyWinApp* app = new MyWinApp();

    app->InitApplication();
    app->InitInstance();

    app->Run();

    AfxWinTerm();

    return 0;
}


class MyWinApp: public CWinApp
{
public:
    BOOL InitInstance();

    int Run();
};


BOOL MyWinApp::InitInstance()
{
    return TRUE;
}

int MyWinApp::Run()
{
    return CWinThread::Run();
}

跳过CWinApp :: Run(),因为它查找主窗口。

但是在CWinThread :: Run()中,ASSERT_VALID失败。在快速监视器的顶部,它说MyWinApp无效。

我是否需要以其他方式创建MyWinApp?

1 个答案:

答案 0 :(得分:3)

您可能失败了,因为您在调用CWinApp 之后创建了AfxWinInit 。在常规MFC应用程序中,CWinApp是一个全局变量,它在main之前构建。这样,当初始化MFC时,它具有有效的全局CWinApp。尝试:

MyWinApp* app = new MyWinApp();   // ^moved up^

// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
    // TODO: change error code to suit your needs
    _tprintf(_T("Fatal Error: MFC initialization failed\n"));
    return nRetCode = 1;
}