Winapi C++;Messagebox中文版
ConsoleApplication.cppWinapi C++;Messagebox中文版,winapi,visual-c++,messagebox,Winapi,Visual C++,Messagebox,ConsoleApplication.cpp // ConsoleApplication2.cpp : Defines the entry point for the console application. // #include "stdafx.h" int main() { std::cout << "Hello World" << std::endl; MessageBox(0, LPTSTR("Text Here"), LPTSTR("T
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int main()
{
std::cout << "Hello World" << std::endl;
MessageBox(0, LPTSTR("Text Here"), LPTSTR("Text Here"), MB_OK);
std::cin.clear();
std::cout << "Press Enter to continue" << std::endl;
std::cin.ignore(32767, '\n');
std::cin.get();
return 0;
}
//ConsoleApplication2.cpp:定义控制台应用程序的入口点。
//
#包括“stdafx.h”
int main()
{
std::cout您的LPTSTR
类型转换是错误的。在使用定义的UNICODE
编译时,MessageBox()
解析为MessageBoxW()
,而LPTSTR
解析为wchar*
,因此您确实在这样做:
MessageBoxW(0, (wchar*)"Text Here", (wchar*)"Text Here", MB_OK);
您正在告诉编译器键入窄字符串,就像它们是宽字符串一样。窄字符串“Text Here”
由字节54 65 78 74 20 48 65 72 65
组成。当这些字节被解释为宽字符串时,它们生成中文字符串敔瑸䠠牥e“
如果要使用基于TCHAR
的API,如MessageBox()
,则在编译时向它们传递字符/字符串文本时需要使用宏,例如:
MessageBox(0, TEXT("Text Here"), TEXT("Text Here"), MB_OK);
定义UNICODE
时,TEXT()
将文本编译为宽文本。未定义UNICODE
时,TEXT()
将文本编译为窄文本
否则,根本不要依赖基于TCHAR
的API。明确使用Ansi/Unicode版本,例如:
MessageBoxA(0, "Text Here", "Text Here", MB_OK);
另请注意:对cin.ignore()
的调用应使用std::numeric\u limits
而不是硬编码长度:
#include <limits>
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
#包括
std::cin.ignore(std::numeric_limits::max(),'\n');
LPTSTR cast只是阻止编译器告诉您您做错了,它并没有阻止您做错。使用L“text”生成使用Unicode的字符串文本。或者使用MessageBoxA()如果您坚持使用ansi字符串。提示:在Visual Studio中,只需通过Ctrl+F5运行您的程序,使控制台窗口在末尾保持不变。这只是在没有调试器的情况下正常运行它(但使用在末尾执行暂停的驱动程序批处理文件)例如,你不需要那么愚蠢的cin
-编码。:@HansPassant:“使用L“text”
生成使用Unicode的字符串文字。”--不,不,不。第一,“Unicode”不是一种编码。例如,UTF-16就是。而L“text”
不是指“Unicode”或UTF-16,只是“wchar\u t
实现定义编码字符串”。@DevSolar:你错了。Hans正在使用。如果你坚持使用TCHAR
,那么正确的宏是TEXT()
,而不是TCHAR()
。
MessageBoxW(0, L"Text Here", L"Text Here", MB_OK);
#include <limits>
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');