afxwin.h issues in Visual Studio 2015 Windows Form App

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 14:14:21

The C runtime library was significantly rewritten for VS2015 by James McNellis. He's a big C++ fan, the new code he's written suffers from the chronic SIOF problem that's so common in a C++ program. The Static Initialization Order Fiasco was surely present in your VS2013 project as well but happened not to byte, the original CRT code was exposed to SIOF for many years so likely to behave better.

Excessively hard to debug in this case, the code that fails comes from a CRT source code file that is not included in the install named thread_safe_statics.cpp. Not 100% sure what it does given that there's no source code to look at but the name of the file leaves little to the imagination.

MFC has static state that needs to be initialized before it is usable. In particular, the program must have a static CWinApp variable that is initialized at Just the Right Time. That requires the entrypoint to be WinMain(), implemented in MFC, and an explicit declaration of a CWinApp instance in your source code. Like this:

[STAThread]
int main(cli::array<System::String^>^ args)
{
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    Application::Run(gcnew Test::MyForm);
}

class MyMfcApp : public CWinApp {
public:
    virtual int Run() override {
        return main(__nullptr);
    }
} MyApp;

Reset the linker's EntryPoint setting back to its default (blank) so the CRT is initialized first and MFC's WinMain function runs next. And beware I took a shortcut, you get no args. And I fixed a bug in your main() function, it used stack semantics incorrectly.

This hack gets your program running again. Whether it is actually correct is rather doubtful. This suffers from the "Who is the Boss" syndrome that's associated with big frameworks. Don't depend on any MFC window to work correctly since it is Winforms that is dispatching messages. But you should have had that problem in VS2013 as well. "Don't do it" is the only solid advice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!