You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义MessageBoxButtons点击逻辑,点击对应按钮后弹出指定提示信息

实现方案

MessageBox.Show() 方法会返回 DialogResult 枚举类型的结果,对应用户点击的按钮选项,你只需捕获这个返回值做分支判断即可实现自定义点击逻辑,修改后的代码如下:

var deliveryTime = sender as MaskedTextBox;

DateTime now = DateTime.Now; // 当前时间
DateTime delTime;
// 优化:用TryParse避免非法时间格式抛出异常
if (!DateTime.TryParse(deliveryTime.Text, out delTime))
{
    MessageBox.Show("请输入正确的时间格式", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
}

if(delTime <= now) 
{
    MessageBox.Show($"无效时间 {delTime.ToShortTimeString()}(时间不能早于当前时间)", "错误", MessageBoxButtons.OKCancel,MessageBoxIcon.Error);
}
else 
{
    // 接收弹窗的点击结果
    DialogResult orderConfirmResult = MessageBox.Show($"您的披萨订单总价为 ${Cost},配送时间为 {delTime},是否确认下单?","订单确认",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
    // 根据点击结果执行对应逻辑
    if (orderConfirmResult == DialogResult.OK)
    {
        MessageBox.Show("订单下单成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        // 这里可以加后续下单的业务逻辑
    }
    else if (orderConfirmResult == DialogResult.Cancel)
    {
        MessageBox.Show("订单已取消", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}

补充说明

  • 如果你需要使用 MessageBoxButtons.YesNo 按钮组,只需将弹窗的按钮参数替换为 MessageBoxButtons.YesNo,后续判断条件对应换成 DialogResult.Yes 和 DialogResult.No 即可,逻辑完全一致
  • 上述代码额外增加了时间格式合法性校验,你可以根据业务需求决定是否保留

内容的提问来源于stack exchange,提问作者Nicholas Grammatopoulos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:57:01