MFC CWnd::Create 触发断言 wincore.cpp

MFC CWnd::Create triggers assertion wincore.cpp

我正在开发一个派生自 CWnd 的 MFC class,并在其构造函数中创建一个隐藏的 window。对象本身是在派生的 CWinApp::InitInstance 函数中构建的。

if (
    this->CWnd::Create(
        nullptr,
        nullptr,
        WS_DISABLED, // Even disabled it will receive broadcast messages.
        {0, 0, 0, 0},
        CWnd::GetDesktopWindow(),
        fakeWindowId
    ) == FALSE
)
      throw runtime_error{"failed to create window"};

当我在调试版本中 运行 这段代码时,它会触发以下断言:

Debug Assertion Failed!

Program: C:\WINDOWS\SYSTEM32\mfc140ud.dll File: f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\wincore.cpp Line: 571

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

如果我忽略断言,代码可以正常工作并且没有观察到不良影响。我该如何解决这个断言?

我也在注册 window 如下:

BOOL HiddenWindow::PreCreateWindow(CREATESTRUCTW& cs)
{
    if ( ! CWnd::PreCreateWindow(cs))
        return FALSE;
    cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
    WNDCLASSEXW wc;
    ZeroMemory(&wc, sizeof(WNDCLASSEXW));
    wc.cbSize = sizeof(WNDCLASSEXW);
    const auto instance{AfxGetInstanceHandle()};

    if (GetClassInfoExW(instance, this->className_.c_str(), &wc) == FALSE)
    {
        wc.lpszClassName = this->className_.c_str();

        if ( ! RegisterClassExW(&wc))
        {
            Logger::Fatal(
                "Registering the window for copy data message failed! Messages will not be "
                    "copied, error code {}.",
                GetLastError()
            );
            return FALSE;
        }
    }
    else
        Logger::Debug(
            "There is already a window registered under the class name '{}'.",
            toString(this->className_)
        );
    cs.lpszClass = _wcsdup(this->className_.c_str());
    return TRUE;
}

所以,我无法弄清楚是什么导致了 MFC 断言。解决方案是完全删除 MFC window,并在 class 下用 Win32 window 替换它,即 CreateWindowExWGetClassinfoExWRegisterClassExW.