如何关闭Visual Basic控制台应用?寻求一行终止执行代码
Hey there! I get it—frustrating when Environment.Exit(0) doesn't work like you expect. Let's break down what's going on and fix this quickly.
First, let's cover the most reliable one-liners to kill your VB console app, then we'll look at why your current code might not be hitting the exit logic.
1. Use the End statement
This is the simplest, most direct way to terminate a VB console application immediately. It stops all execution right where it's called, no questions asked:
End
It cleans up resources and exits the entire process—perfect for console scenarios where you need an immediate shutdown.
2. Make sure Environment.Exit(0) is actually being executed
Chances are, your Environment.Exit(0) line isn't getting reached in your code flow. Let's take your existing Exit_Program sub and fill in the missing pieces to ensure the exit logic triggers when the user types "exit":
Sub Exit_Program() Console.Clear() Console.WriteLine("************************************************") Console.WriteLine(" ") Console.WriteLine("Are you sure you want to exit? if so type 'exit' or type 'back' to get back to the main menu.") Dim userResponse As String = Console.ReadLine().Trim().ToLower() If userResponse = "exit" Then ' This should work if we reach this block Environment.Exit(0) ' 0 indicates a successful, normal exit ' Alternatively, replace with End for even more immediate termination ' End ElseIf userResponse = "back" Then ' Call your main menu sub here to return ' MainMenu() Else Console.WriteLine("Invalid input—try again!") Exit_Program() ' Loop back to prompt if input is bad End If End Sub
If Environment.Exit(0) still doesn't work after this, double-check that:
- You're actually entering "exit" when prompted (case doesn't matter here thanks to
ToLower()) - There are no unhandled exceptions preventing the code from reaching that line (add a
Console.WriteLine("Exiting...")right beforeEnvironment.Exitto verify)
3. What to avoid
Skip Application.Exit()—that's designed for Windows Forms apps, not console applications. It won't work as expected here.
Pick whichever method fits your flow: End for instant termination, or Environment.Exit(0) if you want to specify an exit code (useful for scripting or batch files that check exit statuses).
内容的提问来源于stack exchange,提问作者Tejash

