我们很熟悉使用printf格式化输出信息,然而Win32中输出消息,格式化起来很麻烦,这里就实现了这样一个功能,可以方便的格式化显示MessageBox消息。
vsprintf()函数用来将多参数格式化到一个字符数组中,用来实现sprintf()函数的
自定义格式化消息实现原理如下:
1.定义一个参数列表指针,然后va_start()将指针设置指向格式化字符串上一个位置,即第一个参数的位置。
2.参数列表从szBuff依次压入栈中,参数是在szFormat后压入的,自然就在其上,szBuff就在最底部,最后压栈的就在最上面,这样也就可以动态识别参数的个数和处理。
3.处理时先处理最上面的参数,依次出栈。处理完后va_end()将参数指针重置。就完成了这个功能。用这种方法可以自定义多参数函数。
实现代码如下:
#include "windows.h"
#include <stdio.h>
void print(char * szBuff, const char * szFormat, ...);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
char buf[50] = "";
int n1 = 10;
int n2 = 20;
print(buf, "hello %d ,%d", n1, n2);
MessageBoxA(NULL, "Hello World!", buf, MB_OK);
return 0;
}
void print(char * szBuff, const char * szFormat, ...)
{
va_list pArgs;
va_start(pArgs, szFormat);
vsprintf(szBuff, szFormat, pArgs);
va_end(pArgs);
return;
}
包装一下,将MessageBoxA包装到自定义函数中,使用更加方便。更多精彩文章,欢迎像逛超市一样逛C++技术网,你一定会发现很多精彩的内容哦。
代码如下:
#include "windows.h"
#include <stdio.h>
int Msg(char * szBuff, const char * szCaption, const char * szFormat, ...);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
char buf[50] = "";
int n1 = 10;
int n2 = 20;
Msg(buf, "自定义消息框", "hello ,%d ,%d", n1, n2);
return 0;
}
int Msg(char * szBuff, const char * szCaption, const char * szFormat, ...)
{
va_list pArgs;
va_start(pArgs, szFormat);
vsprintf(szBuff, szFormat, pArgs);
va_end(pArgs);
return MessageBoxA(NULL, szBuff, szCaption, 0);
}