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

 ̄綄美尐妖づ 提交于 2019-12-10 21:32:09

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/2111368/creating-a-win32-window-app-with-english-title-bar-but-the-title-bar-becomes-ch

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