开发者

Creating a Win32 Window app with English title bar, but the title bar becomes Chinese out of nowhere. How come?

开发者 https://www.devze.com 2022-12-17 21:51 出处:网络
HWND wndHandle; //global variable // code 开发者_运维问答snipped WNDCLASSEX wcex; // code snipped
HWND wndHandle; //global variable

// code 开发者_运维问答snipped

WNDCLASSEX wcex;

// code snipped

wcex.lpszClassName = (LPCWSTR) "MyTitleName";

 // code snipped

wndHandle = CreateWindow(
            (LPCWSTR)"MyTitleName",     //the window class to use
            (LPCWSTR)"MyTitleName",     //the title bar text
...
...

I am following a tutorial for Win32 Window application. The code above is used to set the name of the title bar of the window screen. The compiler yells at me : "cannot convert from 'const char [12]' to 'LPCWSTR'" so okay, I typecasted my string "MyTitleName" with (LPCWSTR), and everything compiled just fine. However, during runtime, the title of the window screen turns out to be Chinese characters. I tried change the string around and the Chinese characters always change according to my string somehow. I am using XP Visual C++ 2008 Express Edition and I got English (United States) as a setting for non-unicode programs. I don't get it. How come the string become Chinese?


Your application is being compiled as a unicode application (this is defined in the project settings). This means that strings you pass to Windows API functions need to be wide-character strings, specified like this: L"MyTitleName". You can't cast to LPCWSTR because that won't actually change the string type, it will just try to pass the string off as something it isn't.

This code should work:

wcex.lpszClassName = L"MyTitleName";

 // code snipped

wndHandle = CreateWindow(
            L"MyTitleName",     //the window class to use
            L"MyTitleName",     //the title bar text
            ...

If you want to use the original code from the tutorial without modifying it, you can disable unicode mode: In the project properties go to 'General' tab, and set Character Set to Use Multi-Byte Character Set. Don't do this for any program which might have to support additional languages someday.


That's because of your (LPCWSTR) cast. That just shut the compiler up, telling you that you did something wrong. The string is still not a Unicode string and doesn't get converted by the cast. Fix:

wcex.lpszClassName = L"MyTitleName";
wndHandle = CreateWindow(
              L"MyTitleName",     //the window class to use
              L"MyTitleName",     //the title bar text
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号