Close C# Console Application after MessageBox clic

2019-09-06 20:07发布

问题:

I'm still learning all the cool tricks C# has to offer. I have a messagebox alert that pops up after a timer expires. I'm wondering if it is at all possible to have the console application terminate on its own after the user click the "OK" button on the messagebox. The console app is automatically minimized to the taskbar if that of any circumstance.

Thanks in advance.

回答1:

Give this a go:

// Terminates this process and gives the underlying operating system the specified exit code.
Environment.Exit()

MSDN: Environment.Exit Method



回答2:

Use Environment.Exit()

http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx



回答3:

This is what I would have done.

Wrap your messagebox code into an if statement

    if (MessageBox.Show("error", "error", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
    {
        System.Diagnostics.Process.GetProcessesByName("YOURPROCESSNAME.EXE")[0].Kill();
    }

There is no errorhandling in here, and I take it your console runs as a process. If you use the name of the process your console is running in GetprocessesbyName, you can close it with this method.

To blatantly kill your app (stop process) you can also use Environment.Exit(0) instead of Process.Kill().