Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Why this window title gets truncated?

Tags:

c++

winapi

Visual C++ 2012 RC, Win7

Chinese simplified

Project Properties > use multi byte character set

When I run this program, the window's title shows a single letter "S", not a whole word "Sample".

#pragma comment(linker, "/SubSystem:Windows")

#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PSTR, int) {
    WNDCLASSW wc = { 0 };

    wc.style            = CS_VREDRAW | CS_HREDRAW;
    wc.hInstance        = hInstance;
    wc.hIcon            = LoadIcon(nullptr, IDI_APPLICATION);
    wc.hCursor          = LoadCursor(nullptr, IDC_ARROW);
    wc.hbrBackground    = reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH));
    wc.lpszClassName    = L"MyWindowClass";

    wc.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
        if (uMsg - WM_DESTROY)
            return DefWindowProc(hWnd, uMsg, wParam, lParam);
        else {
            PostQuitMessage(0);
            return HRESULT();
        }
    };

    RegisterClassW(&wc);

    CreateWindowExW(0, L"MyWindowClass", L"Sample",
        WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, SW_SHOW, CW_USEDEFAULT, 0,
        nullptr, nullptr, hInstance, nullptr);

    for (MSG msg; GetMessage(&msg, nullptr, 0, 0); DispatchMessage(&msg));
}

If I use Unicode (Project Properties), keep source code unchanged, window title shows "Sample", looks correct.

If I use multi byte, in source code I use WNDCLASS = { ..., "MyWindowClass" } and RegisterClassA, keep CreateWindowExW unchanged, window title shows word "Sample", looks correct.

If I use multi byte, in source code I use CreateWindowExA("MyWindowClass", "Sample"), keep WNDCLASSW and RegisterClassW unchanged, window title shows letter "S".

What makes it show a single "S", am I doing something wrong?

Append

If I keep all unchanged, that is, use multi byte, use code shown above, window title shows letter "S".

(If you run this program and see "Sample" on window title, rather than "S", then it's more likely a specific problem on chs version of vc++ 2012 (or OS)).

like image 472
WangZm Avatar asked Aug 09 '12 12:08

WangZm


1 Answers

The problem in your code is that you are using DefWindowProc instead of DefWindowProcW. Changing that will fix the code.

Ideally you should change your project settings to use Unicode, not multi-byte character set. This will simplify everything and you can use the macros like CreateWindowEx and RegisterClassEx instead of explicitly using the Unicode / ANSI versions as you are.

As others have said, this is a mismatch between character sets.

You should ideally match character sets between all your API calls that interact with each other. So if you use CreateWindowExW you should also use RegisterClassExW, DefWindowProcW, DispatchMessageW...

like image 158
tenfour Avatar answered Oct 12 '22 10:10

tenfour