在MessageBox中输出变量
2010-08-08
下面程序展示了如何实作MessageBoxPrintf函数,该函数有许多参数并能像printf那样编排它们的格式。使用这个函数可以将变量在MessageBox中输出出来,下面的程序实现了将斐波纳契数列中的第N位数输出出来。
/*-----------------------------------------------------
FibonacciQuery.C -- Displays varible in a message box
(c) Gonn, www.nowamagic.net, 2010
-----------------------------------------------------*/
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include "StdAfx.h"
int fibonacci(int i);
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 (szFormat) ;
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|1) ;
}
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
int nowamagic, result ;
nowamagic = 8;
result = fibonacci(nowamagic);
MessageBoxPrintf (TEXT ("斐波纳契数列查询"),
TEXT ("Fibonacci数列中第%d位的值为%d"),
nowamagic, result) ;
return 0 ;
}
int fibonacci(int i)
{
if(i <= 1)
{
return 1;
}
return fibonacci(i - 1) + fibonacci(i - 2);
}
程序运行结果如下:

MessageBox函数会建立一个「窗口」。在Windows中,「窗口」一词有确切的含义。一个窗口就是屏幕上的一个矩形区域,它接收使用者的输入并以文字或图形的格式显示输出内容。
MessageBox函数建立一个窗口,但这只是一个功能有限的特殊窗口。消息窗口有一个带关闭按钮的标题列、一个选项图标、一行或多行文字,以及最多四个按钮。当然,必须选择Windows提供给您的图标与按钮。
