自定义扩展MessageBox(Formatted MessageBox/AfxMessageBox)

本文介绍了如何在MFC及非MFC环境下创建格式化的消息框。通过使用可变参数列表,可以方便地构建带有格式的字符串并显示为消息框。示例代码展示了如何将变量值插入到字符串中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 文章来自于: http://www.codeproject.com/Tips/120013/Formatted-MessageBox-AfxMessageBox


2.  如果使用了MFC

void AfxMessageBoxFormatted(LPCTSTR pFormatString, ...)
{
    va_list vl;
    va_start(vl, pFormatString);<br>
    CString strFormat;
    strFormat.FormatV(pFormatString, vl); // This Line is important!<br>
    // Display message box.	
    AfxMessageBox(strFormat);
}

//这样使用:
AfxMessageBoxFormatted(_T("Name is %s, Age is %d, and salary is %.2f"), 
   sName, nAge, nSalary);

3. 如果不用MFC

void MessageBoxFormatted(HWND hWnd, LPCTSTR pCaption, LPCTSTR pFormatString, ...)
{
    va_list vl;
    va_start(vl, pFormatString);<br>    
    TCHAR strFormat[1024]; // Must ensure size!<br>

    // Generic version of vsprintf, works for both MBCS and Unicode builds 
    _vstprintf(strFormat, pFormatString, vl);<br>	
    // Or use following for more secure code
    // _vstprintf_s(strFormat, sizeof(strFormat), pFormatString, vl)<br>
    ::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);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值