The problem here is the Win32 TCHAR
model.
There's actually no MessageBox
function: MessageBox
is a preprocessor #define
, that expands to MessageBoxA
or MessageBoxW
, based on your project settings (ANSI/MBCS or Unicode, respectively).
Starting with VS2005, the default setting in Visual Studio has been Unicode (to be more precise: UTF-16). So the MessageBoxW
API (i.e. the Unicode version) is picked in this case by the compiler.
The MessageBoxW
API takes Unicode (UTF-16) strings, represented via wchar_t
pointers (the obscure LPCWSTR
preprocessor macro is expanded to const wchar_t*
, i.e. a NUL
-terminated C-style Unicode UTF-16 string).
Unicode (UTF-16) string literals are represented using the L"..."
syntax (note the L prefix).
So, while "Test_text"
is an ANSI string literal, L"Test_text"
is a Unicode (UTF-16) string literal.
Since your are (implicitly, via Visual Studio default settings) doing a Unicode build, you should decorate your string literals with the L prefix, e.g.:
MessageBox(nullptr, // <--- prefer nullptr to NULL in modern C++ code
L"Test_text", // <--- Unicode (UTF-16) string literal
L"Message Test", // <--- Unicode (UTF-16) string literal
MB_ICONINFORMATION | MB_OKCANCEL);
An alternative is to decorate the string literals using the _T("...")
or TEXT("...")
macros. These will be expanded to simple "..."
ANSI string literals in ANSI/MBCS builds, and to Unicode (UTF-16) string literals L"..."
in Unicode builds (which are the default in modern versions of Visual Studio).
// TEXT("...") works in both ANSI/MBCS and Unicode builds
MessageBox(nullptr,
TEXT("Test_text"),
TEXT("Message Test"),
MB_ICONINFORMATION | MB_OKCANCEL);
Personally, I consider the TCHAR model an obsolete model from the past (I see no reason to produce ANSI builds of modern C++ Win32 applications), and considering that modern Windows APIs are Unicode-only (e.g. DrawThemeText()
), I'd just decorate strings literals using the L"..."
prefix, and kind of forget about the ANSI builds.