J.Doe J.Doe - 7 days ago 5
C# Question

Application.Exit Isn't closing my program, any alternatives?

So in my form constructor I have a check for an argument. If I get one of two special arguments then I want to just register/unregister my server and close the program. I don't want the form to load in these instances. However as it currently stands the following code successfully registers/unregisters the server, but it doesn't kill my application right after like I want it to. Any other command to do so? Or maybe there's a better way to do what I'm trying to do?

My code:

public Form1()
{
InitializeComponent();
instance = this;
fillMeasView();

string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
switch (args[1])
{
case "register":
try
{
slikServer1.RegisterServer();
MessageBox.Show("Server registered successfully!");
}
catch(Exception ex)
{
MessageBox.Show("Error: Could not register server." + "\nAdditional Information: " + ex.Message, "Registering Server Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Application.Exit();
break;
case "unregister":
try
{
slikServer1.UnregisterServer();
MessageBox.Show("Server unregistered successfully!");
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not unregister server." + "\nAdditional Information: " + ex.Message, "Unregistering Server Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Application.Exit();
break;
default:
MessageBox.Show("This is the cmd line arg:" + args[1]);
break;
}
}

}

Answer

You want:

Environment.Exit(0);