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;
}
You have to tell Windows how large your
WNDCLASSEX
structure is by filling in thecbSize
member. You failed to initialize this member before callingRegisterClassEx
, which is presumably why that function is failing. Thesizeof
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 theRegisterClassEx
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 aWNDCLASSEX
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 theRegisterClassEx
function. This will help you to debug problems when you encounter them.Working sample code: