在WNDCLASSEX中向WndProc回调添加代码会破坏代码

时间:2012-10-17 18:54:26

标签: c++ user-interface system

我有这个代码,它是我创建的用户界面系统的一部分,它将有多个窗口

bool UISystem::HandleMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    UIWindow* target = NULL;
    for(vector<UIWindow*>::iterator it = windowList.begin(); it < windowList.end(); it++)
    {
        if((*it)->windowHandle == hwnd)
        {
            target = *it;
            break;
        }
    }

    if(target == NULL)
    { return false; }

    switch(msg)
    {
    case WM_DESTROY:

        return true;

    case WM_PAINT:  

        return true;

    default:
        return false;
    }
}

LRESULT WINAPI UISystem::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    /*if(UISYSTEM->HandleMessage(hwnd, msg, wParam, lParam))
    {
    }*/
    return DefWindowProc(hwnd, msg, wParam, lParam);
}

当这个代码按原样实现时,包括UISystem :: WndProc中的注释块,会正确显示一个窗口,但是如果我在UISystem :: WndProc中取消注释这个块,那么从CreateWindow返回一个无效句柄。我很感激,因为这让我很困惑,在UISystem :: WndProc中我做任何其他代码之前我曾尝试调用DefWindowProc,但我的所有尝试都失败了

这是UIWindow的构造函数:

UIWindow::UIWindow(int x, int y, int width, int height, string & text)
{

    int frameWidth   = GetSystemMetrics(SM_CXSIZEFRAME);
    int frameHeight  = GetSystemMetrics(SM_CYSIZEFRAME);
    int menuHeight   = GetSystemMetrics(SM_CYMENU);
    int windowXPos   = (GetSystemMetrics(SM_CXSCREEN) - width) / 2;
    int windowYPos   = (GetSystemMetrics(SM_CYSCREEN) - height) / 2;
    int windowWidth  = width + frameWidth * 2;
    int windowHeight = height + frameHeight * 2 + menuHeight;

    bounds.X = x;
    bounds.Y = y;
    bounds.Width = width;
    bounds.Height = height;
    title = text;

    MSG msg;

    WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_VREDRAW|CS_HREDRAW|CS_OWNDC, 
        &UISystem::WndProc, 0, 0, hInstance, NULL, NULL, (HBRUSH)(COLOR_WINDOW + 1), 
        NULL, "AurousWindow", NULL};

    RegisterClassEx(&wc);


    windowHandle = CreateWindow("AurousWindow", title.c_str(), WS_OVERLAPPEDWINDOW, windowXPos, windowYPos, windowWidth, windowHeight, NULL, NULL, hInstance, NULL);
    SetWindowRgn(windowHandle, CreateRectRgn(0, 0, width, height), TRUE);
    ShowWindow(windowHandle, nShow);
    UpdateWindow(windowHandle);

    //RECT rec = {0, 0, width, height};

    while(GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

1 个答案:

答案 0 :(得分:1)

不确定这是否是根本问题,但您应该解决的一件事是删除:

while(GetMessage(&msg, NULL, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

从:

UIWindow::UIWindow(int x, int y, int width, int height, string & text)

只要您的窗口存在,它就会循环,并且会阻止UIWindow正确构造。这个对象(UIWindow)实际上是在内部访问的:UISystem :: HandleMessage,但由于它的构造函数永远不会结束,所以它可能是NULL或处于未定义状态。