Monday, March 28, 2011

c# one Form blocking another in a winform Project

I have an application which uses 2 forms, a Main Form and a Splash Form being used in the following configuration:

public class MainForm : Form
{
    public MainForm()
    {
       SplashScreen splash = new SplashScreen();

       // configure Splash Screen
    }
}


public class SplashScreen
{
    public SplashScreen()
    {
       InitializeComponent();

       // perform initialization

       this.ShowDialog();
       this.BringToFront();
    }
}

NB: Main form is created with the following code:

Application.Run( new MainForm() );

The problem above is that the configuration of splash does not occur unless splash is closed with

splash.Close();

only when this occurs does the rest of the MainForm constructor run. how can I easily stop this blocking behaviour?

From stackoverflow
  • Use splash.Open() rather than splash.OpenDialog() and this won't happen.

  • Generally, you need to show splash screens on a separate thread, and let the primary thread carry on with loading. Not trivial - in particular, you will need to use Control.Invoke to ask the splash screen to close itself when ready (thread affinity)...

  • Basically, you want to just show you splash form, but not let it block the main form.

    Here's how I've done it:

    class MainForm : Form {
    
        SplashScreen splash = new SplashScreen();  //Make your splash screen member
    
        public MainForm()
        {
            splash.Show();  //Just show the form
        }
    
    }
    

    Then in your MainForm_Load you do your initialization as normal.

    Now when your form is ready to be displayed (MainForm_Shown):

    public MainForm_Shown()
    {
        splash.Close();
    }
    

    This lets your MainForm load normally while displaying the splash screen.

  • I already replied to you with a working example on the other question you asked for the same thing:

    http://stackoverflow.com/questions/510765/510786#510786

    TK : Apologies. This is a different problem to the above question, although you are correct in saying your solution might work for this problem as well. I will have to give it a try.

0 comments:

Post a Comment