格式化的消息框

MessageBoxPrintf 函数的实现.

// Build with VS2008withSP1, /W4 #include <windows.h> #include <tchar.h> #include <cstdio> #include <cstdarg> int CDECL MessageBoxPrintf(TCHAR* szCaption, TCHAR* szFormat, ...) { TCHAR* pBuffer(NULL); int nLength(-1); int nRet(0); va_list pArgList; va_start(pArgList, szFormat); nLength = _vsctprintf(szFormat, pArgList) + 1; // The returned value of _vsctprintf // does NOT include the terminating // null character. pBuffer = new TCHAR[sizeof(TCHAR) * nLength](); if (NULL == pBuffer) { MessageBox(NULL, TEXT("Memory allocation failed!"), TEXT("Error"), MB_OK | MB_ICONERROR); return 0; // If the function MessageBox fails, the return value is zero. } _vstprintf_s(pBuffer, nLength, szFormat, pArgList); va_end(pArgList); nRet = MessageBox(NULL, pBuffer, szCaption, 0); delete [] pBuffer; pBuffer = NULL; return nRet; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hInstance); UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(szCmdLine); UNREFERENCED_PARAMETER(nCmdShow); int cxScreen(-1); int cyScreen(-1); cxScreen = GetSystemMetrics(SM_CXSCREEN); cyScreen = GetSystemMetrics(SM_CYSCREEN); MessageBoxPrintf(TEXT("ScrnSize"), TEXT("The screen is %d pixels wide by %d pixels high. "), cxScreen, cyScreen); return 0; }

输出

格式化的消息框_第1张图片

相关函数

  • vsprintf, vswprintf, _vstprintf; vsprintf_s, vswprintf_s, _vstprintf_s;
  • _vscprintf, _vscwprintf, _vsctprintf;
  • vsnprintf, _vsnprintf, _vsnwprintf, _vsntprintf; vsnprintf_s, _vsnprintf_s, _vsnwprintf_s, _vsntprintf_s.

参考

《Windows 程序设计(第五版 珍藏版)》Page34.

你可能感兴趣的:(function,null,delete,include,Allocation,winapi)