BenevolentDeity
BenevolentDeity

Reputation: 783

C# - Manually closing a forms application

I would like to know the appropriate way to completely terminate a Forms application. I open the form in the standard way using the code:

namespace History
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new DisplayHistory());
        }
    }
}

...and here is a barebones version of the DisplayHistory function with the various things I've tried to terminate the application commented out. The first two cause an unhandled exception stating that I cannot access a disposed object. The third one has no effect at all, and the fourth one won't compile at all because I get an error saying that "Application does not contain a definition for Current":

public DisplayHistory()
{
    InitializeComponent();

//    this.Close();
//    Close();
//    Application.Exit();
//    Application.Current.Shutdown();
}

Upvotes: 1

Views: 1866

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125187

Instead of trying to close it in constructor, it's better not to open the form.

But if you really want to close the form in constructor based on some condition, you can subscribe for Load event before InitializeComponent in code and close the form using this.Close() :

public Form1()
{
    if (some criteria)
    {
        this.Load += (sender, e) => { this.Close(); };
    }
    return;

    InitializeComponent();
}

To close an application normally, you can call below codes anywhere except constructor of form:

  • this.Close();
  • Application.Exit();

To force the application to stop, or close it abnormally, you can call Environment.Exit anywhere including the form constructor:

  • Environment.Exit(1);

Upvotes: 3

Related Questions