Search code examples
c#formssplash-screen

.NET Login and Splash Screens what to put in Application.Run


In .NET (language: C#) when writing Windows Applications we start the application with a form passed to Application.Run.

But when you have an Application where you don't have a single window to keep it alive... But rather if any of one type of forms is active you wan't the application to remain.

What I have is e.g. a Login Screen that when the user successfully log's in, I wan't to close. However calling "Close()" obviously closes the entire app since the login screen is the one passed to the Application.Run.

The next screen has the same "fate" so can't use that either, that will be a screen where the user selects something and then it closes.

Anyways... long story short. I have a few ideas, but all involving some not so neat things. So what I am asking for here is sort of a "Best Practice" in these cases. This is not something with a definitive awnser, I know that, so please all good ideas are welcome and discussions around them.


Solution

  • The Code Project article ended up being the basis for the solution (as it is now).

    There is still some parts to sort out in the "Navigator" part, but the override of the context works perfectly.

    The essence of the implementation:

    public class ApplicationContextNavigator : ApplicationContext, INavigator
    {
      private readonly IWindsorContainer container;
      private IView Current { ... }
      public ApplicationContextNavigator(IWindsorContainer container) {...}
      public void Start<TView>() where TView : IView { ... }
      public void Start<TView>(IViewInitializer initializer) where TView : IView
      {
        Current = InitializeView<TView>(initializer);
        Application.Run(this);
      }
    
      public void Navigate<TView>() where TView : IView { ... }
      public void Navigate<TView>(IViewInitializer initializer) where TView : IView
      {
        IView closing = Current;
        IView showing = InitializeView<TView>(initializer);
    
        showing.Location = closing.Location;
        showing.Show();
    
        Current = showing;
        closing.Close();
      }
    
      private IView InitializeView<TView>(IViewInitializer initializer) where TView : IView
      {
        IView view = container.Resolve<TView>();
        initializer.Initialize(view);
        return view;
      }
    
      protected override void OnMainFormClosed(object sender, EventArgs e)
      {
        if(sender == Current)
        {
          base.OnMainFormClosed(sender, e);
        }
      }
    }