Search code examples
c#.netwinformsmessage-pump

Application.Run not Working after Application.Exit on the same thread


The requirement in my work is to first show a splash screen which takes in a some data from user, authenticates him and starts another form. So, I am starting the splash screen with Application.Run and once, it has done its done, call Application.Exit and then call Application.Run again for the new form. But, this doesn't start the new form. I have a create a new thread and assign its ApartmentModel as STA to start the new form.

I would like to understand why is Application.Run not working after calling Application.Exit?

Sample Code:

        Application.Run(SplashForm);  

        if (_authorizationSuccessful)
            Application.Run(new Form2())
        else
        {
            //just close
        }

Solution

  • It is fairly convoluted, but the core issue that it isn't actually a Form that keeps an Application alive. The core helper class is ApplicationContext, also exposed as one of the overloads of Application.Run(). When you use the other overloads, Run() and Run(Form), the Application class creates a hidden instance of ApplicationContext. Which is global, like all of the Application properties and methods.

    So when you call Application.Exit(), you mark that global instance of ApplicationContext as "no longer active". Which makes the next call to Run(Form) immediately exit.

    You can monkey with your own ApplicationContext instances instead to solve this issue. But the boilerplate solution is to use the ShowDialog() method on the login form. Also a good way to return the "login is good, let's continue" state, the DialogResult is useful.