1、MessageBoxA 和 MessageBoxW
1.1、代码实例
WINUSERAPI
int
WINAPI
MessageBoxA(
__in_opt HWND hWnd,
__in_opt LPCSTR lpText,
__in_opt LPCSTR lpCaption,
__in UINT uType);
WINUSERAPI
int
WINAPI
MessageBoxW(
__in_opt HWND hWnd,
__in_opt LPCWSTR lpText,
__in_opt LPCWSTR lpCaption,
__in UINT uType);
#ifdef UNICODE
#define MessageBox MessageBoxW
#else
#define MessageBox MessageBoxA
#endif // !UNICODE 函数讲解并例子
MessageBoxA 和 MessageBoxW 是 Windows API 中用于显示消息框的函数,分别用于处理 ANSI 字符集(A 表示 ANSI)和 Unicode 字符集(W 表示 Wide)。
1.2、MessageBoxA 函数
int WINAPI MessageBoxA(
HWND hWnd,
LPCSTR lpText,
LPCSTR lpCaption,
UINT uType
);
- hWnd: 指定消息框的父窗口句柄。可以为 NULL。
- lpText: 指定消息框中显示的文本。
- lpCaption: 指定消息框的标题栏文本。
- uType: 指定消息框的样式和按钮,例如 MB_OK 表示只有一个确定按钮。
1.3、MessageBoxW 函数
int WINAPI MessageBoxW(
HWND hWnd,
LPCWSTR lpText,
LPCWSTR lpCaption,
UINT uType
);
- 参数和功能同 MessageBoxA,但处理的是宽字符集(Unicode)。
1.4、条件编译
#ifdef UNICODE
#define MessageBox MessageBoxW
#else
#define MessageBox MessageBoxA
#endif // !UNICODE
这段代码通过 #ifdef UNICODE 条件编译,根据编译时是否定义了 UNICODE 宏来选择使用 MessageBoxW 还是 MessageBoxA。
1.5、示例代码
#include <windows.h>
int main() {
LPCWSTR wideText = L"Hello, this is a wide character string!";
LPCWSTR wideCaption = L"MessageBox Example";
// 使用 MessageBoxW 显示 Unicode 字符串消息框
MessageBox(NULL, wideText, wideCaption, MB_OK);
#ifndef UNICODE
LPCSTR narrowText = "Hello, this is an ANSI character string!";
LPCSTR narrowCaption = "MessageBox Example";
// 使用 MessageBoxA 显示 ANSI 字符串消息框
MessageBox(NULL, narrowText, narrowCaption, MB_OK);
#endif
return 0;
}
在上述示例中,根据是否定义了 UNICODE 宏,选择调用相应版本的 MessageBox 函数。在实际开发中,如果你使用宽字符字符串,建议使用 MessageBoxW 函数以支持 Unicode。
2、LPCWSTR宽字符字符串(Unicode) 与 LPCSTR窄字符字符串(ANSI) 的转换
LPCWSTR 和 LPCS

本文详细介绍了WindowsAPI中的MessageBoxA和MessageBoxW函数,以及宽字符(LPCWSTR)与窄字符(LPCSTR)的转换,包括MultiByteToWideChar,WideCharToMultiByte,mbstowcs,wcstombs等函数的使用和注意事项。
787

被折叠的 条评论
为什么被折叠?



