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

VB MessageBox Yes/No按钮异常:点击No误关目标窗体而非消息框

问题排查与解决方案

Hey David, let's break down why clicking the No button is closing your intended form instead of just dismissing the MessageBox, and fix it right up!

What's Going Wrong in Your Code?

Looking at your current logic, the issue comes from two key mistakes:

  1. Unnecessary (and harmful) code in the No branch: You’ve added frmDuneTours.Visible = False and Me.Visible = True here, but these lines are totally redundant—and even risky. When you click No, all you want is to close the MessageBox and keep your current form (Me) open. The Me.Visible = True does nothing because your form is already visible, and hiding frmDuneTours might mess up your app's state if that form was already open.
  2. Potential app termination in the Yes branch: If Me is your app's startup form, calling Me.Close() first before showing frmDuneTours will shut down the entire application immediately—your frmDuneTours.Visible = True line won’t even run because the program exits.

Fixed Code

Here’s the corrected version that matches your intended behavior:

Private Sub btnMain_Click(sender As Object, e As EventArgs) Handles btnMain.Click
    Dim result As DialogResult = MessageBox.Show("Did you save customer info?", "Save Information", MessageBoxButtons.YesNo, MessageBoxIcon.Stop)
    
    If result = DialogResult.Yes Then
        ' Show the target form FIRST, then close the current one (prevents app shutdown)
        frmDuneTours.Visible = True
        Me.Close()
    ' No branch: DO NOTHING. The MessageBox will automatically close, and your current form stays open
    End If
End Sub

Key Fixes Explained

  • Removed the unnecessary No branch: When you click No, the MessageBox closes on its own, and your current form remains exactly as it was—no extra code needed here.
  • Reordered form operations in Yes branch: By showing frmDuneTours before closing Me, you ensure that if Me is your startup form, the app doesn’t terminate (since there’s still an open form). If you want to make this behavior bulletproof, adjust your project’s shutdown mode:
    • Right-click your project → Properties → Application tab → Shutdown mode → Select When the last form closes

This way, your app will only exit when all open forms are closed, no matter which one was the startup form.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:11:38