MessageBox を printf 形式の書式が使えるようにする例。デバッグなどに役立つ。
#include <windows.h>
#include <tchar.h>
static const char MessageBoxTitle[] = "AppTitle";
void MessageBoxf(char *format, ...);
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance
, LPTSTR lpCmdLine, int nCmdShow)
{
MessageBoxf("%s(%d)", __FILE__, __LINE__);
}
void MessageBoxf(char *format, ...)
{
char buf[1024+1];
va_list args;
va_start(args, format);
#ifdef _MSC_VER
vsprintf_s(buf, sizeof(buf), format, args); // Microsoft Visual C
#else
wvsprintf(buf, format, args); // WIN32 API
// vsprintf(buf, format, args); // C Runtime Function
#endif
MessageBox(NULL, buf, MessageBoxTitle,
MB_ICONEXCLAMATION | MB_APPLMODAL | MB_OK | MB_SETFOREGROUND);
va_end(args);
}
注意:vsprintf と同等の機能を持つものに、いくつか種類があるので適宜つかい分けるといい。
| vsprintf | 標準Cランタイム版。ほとんどのCコンパイラで使える。 |
| wvsprintf | WIN32 API版。1024 バイトを超える結果は切り捨てられます。 |
| vsprintf_s | 最近の Microsoft Visual C版。バッファ オーバーフロー対策してあります。 |
| wvsprintf_s | そんなのありません。 |