该函数能像 printf 那样接收各种各样大量的参数并对它们进行格式化。
源代码:
#include<windows.h>
#include<tchar.h>
#include<stdio.h>
int CDECL MessageBoxPrintf(TCHAR * szCaption, TCHAR * szFormat, ...)
{
TCHAR szBuffer[1024];
va_list pArgList;
//The va_start macro(defined in STDARG.H )is usually equivalent to;
//pArgList = (char *) &szFormat + sizeof(szFromat);
va_start(pArgList,szFormat);
//The last argument to wvsprintf points to the arguments
_vsntprintf(szBuffer, sizeof(szBuffer)/sizeof(TCHAR),
szFormat,pArgList);
//The va_end macro just zeroes out pArgList for no good reason
va_end(pArgList);
return MessageBox(NULL,szBuffer,szCaption,0);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
int cxScreen, cyScreen;
cxScreen = GetSystemMetrics(SM_CXSCREEN);
cyScreen = GetSystemMetrics(SM_CYSCREEN);
MessageBoxPrintf(TEXT("ScrnSize"),TEXT("The screen is %i pixels wide by %i pixels high."),cxScreen,cyScreen);
return 0;
}
运行结果如下:
这个程序以像素为单位显示了视频显示器的宽度和高度,这些像素是从 GetSystemMetrics 函数得到的。
注意,_vsntprintf 的调用。它的第二个参数是字符缓冲区的长度。通常,你会使用 sizeof ( szBuffer ), 但如果缓冲区中有宽字符(2个字节),那么它返回的将不是缓冲区的字符长度,而是缓冲区按字节计算的长度。所以必须把返回值除以 sizeof (TCHAR ) 以得到正确的字符串长度。
本文介绍了一个自定义函数MessageBoxPrintf,它可以像printf一样处理大量格式化参数,并通过消息框展示出来。文章展示了如何利用_vsntprintf进行安全的格式化输出,并给出了完整的示例代码。
&spm=1001.2101.3001.5002&articleId=9106309&d=1&t=3&u=e8ac4fcfbda041589a12d4c01dcbd9b7)
74

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



