How to exit a Windows Forms application immediately after displaying a MessageBox when an error occurs at startup?

When starting the Windows Forms application, I read the XML file. If this file does not exist or does not have a specific parameter, I want to show the MessageBox to the user pointing to the problem, and then close the application.

I tried to do this in a Loadmain form event using Application.Exit()as follows:

private void MainForm_Load(object sender, EventArgs e)
{
    if (!StartupSettingsCorrect())
    {
        MessageBox.Show("Blabla... Can't start application.");
        Application.Exit();
    }

    // Other stuff...
}

But it does not seem clean. (The application works, but is "invisible" without a form on the screen.)

What is the best way and place for a clean shutdown in this situation?

Thank you for your help!

+3
source share
7 answers

Environment.Exit() . , .

MSDN

.

+10

XML Program.cs( ). , .

    static void Main ()
    {
        if ( !StartupSettingsCorrect())
        {
            MessageBox.Show( "Blabla... Can't start application." );
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault( false );
            Application.Run( new MainForm() );
        }
    }
+3

, .

, MessageBox.

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        if (!StartupSettingsCorrect())
        {
            MessageBox.Show("Blabla... Can't start application.");
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
+2

Application.Exit . , , . Application.Exit , .

- . Application.Shutdown.

Environment.Exit. , finally. , .

+1

Environment.Exit() .

Winforms Application.Exit()

, , "colinsmith", !

+1

Form_Load:

Me.Visible = False

if yourCheckNotOk then
  MessageBox("check failed..")
  Me.close()
else
  ...
  ...
  ...
  Me.Visible = True
end if

VS 2010. (, Shutdown " " " " )

0

Form.Dispose() , .

private void MainForm_Load(object sender, EventArgs e)
{
    if (!StartupSettingsCorrect())
    {
        MessageBox.Show("Blabla... Can't start application.");
        Me.Dispose();
    }

    // Other stuff...
}

, .

0

Source: https://habr.com/ru/post/1773031/


All Articles