Win32 API - RegisterClassEx errors

本小妞迷上赌 提交于 2019-12-12 19:21:24

问题


I'm trying to open a simple window through the Win32 API, using the VC++ compiler and in Visual Studio. I'd like to know why the class fails; I've tried allocating it without a pointer, along with allocating it as a pointer and sending it to the function as a reference. Yet, no matter what I try, the RegisterClassEx function refuses to return true.

Why is this, and what can be done about it?

From WinMain

WNDCLASSEX* wc = new WNDCLASSEX;
    HWND hwnd;
    MSG     msg;
    bool    done;

    wc->style = CS_HREDRAW | CS_VREDRAW;
    wc->lpfnWndProc = WndProc;
    wc->cbClsExtra = 0;
    wc->cbWndExtra = 0;
    wc->hInstance = hInstance;
    wc->hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc->hCursor = LoadCursor(NULL, IDC_ARROW);
    wc->hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
    wc->lpszClassName = L"someclass";

    if (!RegisterClassEx(wc)) {
        MessageBox(NULL, L"Class registration has failed!", L"Error!", MB_OK | MB_ICONINFORMATION);
        return 0;
    }

回答1:


You have to tell Windows how large your WNDCLASSEX structure is by filling in the cbSize member. You failed to initialize this member before calling RegisterClassEx, which is presumably why that function is failing. The sizeof operator is all you need.

You also failed to initialize some of the other members of the structure, like lpszMenuName. If you don't explicitly initialize them, they contain garbage data, which is probably causing the RegisterClassEx function to fail. If you're not using them, you need to explicitly set them to 0.

Furthermore, just because the RegisterClassEx argument accepts a pointer to a WNDCLASSEX structure doesn't mean that you have to create the structure as a pointer. You can create a regular object on the stack and use the address-of operator (&) to pass a pointer to the function.

Note that, as per the documentation, you can also call the GetLastError function to get more details on what went wrong when calling the RegisterClassEx function. This will help you to debug problems when you encounter them.

Working sample code:

WNDCLASSEX wc    = {0};  // make sure all the members are zero-ed out to start
wc.cbSize        = sizeof(wc);
wc.style         = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc   = WndProc;
wc.hInstance     = hInstance;
wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
wc.lpszClassName = L"someclass";

if (!RegisterClassEx(&wc)) {
    MessageBox(NULL, L"Class registration has failed!",
               L"Error!", MB_OK | MB_ICONERROR);
    return 0;
}


来源:https://stackoverflow.com/questions/8775443/win32-api-registerclassex-errors

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