Formatted MessageBox/AfxMessageBox






4.87/5 (7 votes)
Need to Format/sprintf a string before displaying a messagebox? Here is solution!
You often need to format a string and populate it with relevant data before displaying a message box. For example
int nAge = 27; TCHAR sName[]="Ajay"; float nSalary = 12500.50; // Declare variable CString strMessage;What if this can be acheived by single statement:
// Format strMessage.Format( _T("Name is %s, Age is %d, and salary is %.2f"), sName, nAge, nSalary);
// Then display. AfxMessageBox(strMessage);
AfxMessageBoxFormatted(_T("Name is %s, Age is %d, and salary is %.2f"), sName, nAge, nSalary);And here is implementation of
AfxMessageBoxFormatted
:void AfxMessageBoxFormatted(LPCTSTR pFormatString, ...) { va_list vl; va_start(vl, pFormatString);If you don't you MFC, or don't want to use, you can implement
CString strFormat; strFormat.FormatV(pFormatString, vl); // This Line is important!
// Display message box. AfxMessageBox(strFormat); }
MessageBoxFormatted
as:
void MessageBoxFormatted(HWND hWnd, LPCTSTR pCaption, LPCTSTR pFormatString, ...) { va_list vl; va_start(vl, pFormatString);And use it as:
TCHAR strFormat[1024]; // Must ensure size!
// Generic version of vsprintf, works for both MBCS and Unicode builds _vstprintf(strFormat, pFormatString, vl);
// Or use following for more secure code // _vstprintf_s(strFormat, sizeof(strFormat), pFormatString, vl)
::MessageBox(hWnd, strFormat, pCaption,MB_ICONINFORMATION); }
MessageBoxFormatted(NULL, // Or a valid HWND _T("Information"), _T("Name is %s, Age is %d, and salary is %.2f"), sName, nAge, nSalary);If you don't understand stuff like
TCHAR
, LPCTSTR
, _T
, you better read this Tip/Trick: What are TCHAR, WCHAR, LPSTR, LPWSTR, LPCTSTR etc?[^]