Daniel Vincent
Daniel Vincent

Reputation: 31

Close C# Console Application after MessageBox click

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.

Upvotes: 0

Views: 2342

Answers (3)

Richard
Richard

Reputation: 8280

Give this a go:

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

MSDN: Environment.Exit Method

Upvotes: 5

Eon
Eon

Reputation: 3974

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().

Upvotes: 0

dtsg
dtsg

Reputation: 4459

Use Environment.Exit()

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

Upvotes: 4

Related Questions