rgolden
rgolden

Reputation: 149

Window not opening

I really have two questions; one is much broader than the other. First, at the top of my code, I've used #define for naming my window class. On MSDN they recommend using "const wchar_t CLASS_NAME[]" down in the main function, but I couldn't get that to work. Does this have something to do with Unicode (I've had problems with the lpsz stuff as well which seems to be related to that perhaps)? Anyway, point being, I can't figure out why that didn't work. It gave an error saying "Cannot assign const wchar_t to LPCSTR."

My second, and more broad question is, even in the state the code is in below, I debug with no errors and run, but no window opens. I cannot figure out what's missing. Any help would be much appreciated. Thanks.

#include <Windows.h>

#define CLASS_NAME TEXT("Window Class")

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR lpCmdLine, int nCmdShow)
{
    MSG msg;

    //Registering the window class.//

    WNDCLASS wc = {};
    wc.lpfnWndProc = DefWindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = CLASS_NAME;
    wc.lpszMenuName = NULL;
    RegisterClass(&wc);

    if (!S_OK)
    {
        return 0;
    }

    //Create Window//

    HWND hwnd = CreateWindowEx(0, "CLASS_NAME", NULL, NULL, 100, 100, 800, 600, NULL, NULL, hInstance, NULL);

    if (hwnd == NULL)
    {
        return 0;
    }

    //Show Window//

    ShowWindow(hwnd, nCmdShow);


    //Message loop//

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

    return msg.wParam;
}

Upvotes: 0

Views: 120

Answers (1)

IInspectable
IInspectable

Reputation: 51345

The code in question terminates right after registering a window class. It never even creates a window. The issue is the following attempt at error handling:

    if (!S_OK)
    {
        return 0;
    }

S_OK is a COM HRESULT value, that evaluates to the constant value 0. Consequently, !S_OK evaluates to true, so that branch is always taken, exiting the user-provided entry point. The compiler issues warning C4127 ("conditional expression is constant") at warning level 4 (which you should be using if at all possible).

Your first question is about mismatching character types (and encodings). The rules are documented under working with strings.

Upvotes: 3

Related Questions