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:
- Unnecessary (and harmful) code in the No branch: You’ve added
frmDuneTours.Visible = FalseandMe.Visible = Truehere, 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. TheMe.Visible = Truedoes nothing because your form is already visible, and hidingfrmDuneToursmight mess up your app's state if that form was already open. - Potential app termination in the Yes branch: If
Meis your app's startup form, callingMe.Close()first before showingfrmDuneTourswill shut down the entire application immediately—yourfrmDuneTours.Visible = Trueline 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
frmDuneToursbefore closingMe, you ensure that ifMeis 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
相关产品推荐
相关产品推荐

