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

C# 弹出MessageBox后如何停止后续代码执行且不退出应用

C#代码流程终止解决方案

你可以根据代码所在的业务场景选择以下两种实现方案:

方案1:使用return语句(最常用,适合独立逻辑方法场景)

如果你的这两段判断逻辑封装在一个独立的导出处理方法中,仅需要终止当前导出流程、不影响方法外的其他业务逻辑,直接在每处loadingLbl.Hide();后新增return;即可。return会直接终止当前方法的执行,既不会运行当前分支后的剩余代码,也不会触发后续的plate导出判断,且不会退出整个应用。

修改后的代码示例:

if (shaftPdfCB.Checked == true)
{
    Operation.RunMacro("shaftCheck.cs");
    if (SelectedDrawings.GetSize() == 0)
    {
        MessageBox.Show("Error, no shaft drawings to export.");
        loadingLbl.Hide();
        return; // 新增此行终止当前方法执行
    }
    else
    {
        Operation.RunMacro("ExportShaft2.cs");
    }
}

if (platePdfCB.Checked == true)
{
    Operation.RunMacro("plateCheck.cs");

    if (SelectedDrawings.GetSize() == 0)
    {
        MessageBox.Show("Error, no plate drawings to export.");
        loadingLbl.Hide();
        return; // 新增此行终止当前方法执行
    }
    else
    {
        Operation.RunMacro("ExportPlate.cs");
    }
}

方案2:使用标志位(适合当前方法后续还有其他需执行逻辑的场景)

如果这两段判断所在的方法后续还有其他需要保留执行的代码,不能直接return,可以新增布尔变量作为终止标志,对后续逻辑做拦截判断。
完整代码示例:

// 两段判断前新增标志位
bool isProcessAbort = false;

if (shaftPdfCB.Checked == true)
{
    Operation.RunMacro("shaftCheck.cs");
    if (SelectedDrawings.GetSize() == 0)
    {
        MessageBox.Show("Error, no shaft drawings to export.");
        loadingLbl.Hide();
        isProcessAbort = true; // 标记流程终止
    }
    else
    {
        Operation.RunMacro("ExportShaft2.cs");
    }
}

// 后续所有需要拦截的逻辑都先判断标志位
if (platePdfCB.Checked == true && !isProcessAbort)
{
    Operation.RunMacro("plateCheck.cs");

    if (SelectedDrawings.GetSize() == 0)
    {
        MessageBox.Show("Error, no plate drawings to export.");
        loadingLbl.Hide();
        isProcessAbort = true; // 标记流程终止
    }
    else
    {
        Operation.RunMacro("ExportPlate.cs");
    }
}

// 方法后续的其他逻辑如果需要拦截也可以加 !isProcessAbort 判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:54:07