Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a splash screen

The concept of a splash screen doesn't strike me as something that should be so complicated, but I'm having trouble getting the whole splash screen painted.

Let's say I have two System.Windows.Forms.Forms: RealForm and SplashScreen. The RealForm contains the initial GUI. During the RealForm's loading process (that is, in the event handler for the Load event), RealForm creates a connection to a database and then tests the connection. This can take several seconds, so before I do all of this, I try to throw up a splash screen like so:

private void RealForm_Load(object sender, EventArgs e)
{
    SplashScreen splash = new SplashScreen();
    splash.Show();
    loadAndCheckDatabase();
    splash.Close();
}

The problem is that the splash screen only gets partially drawn and so it doesn't really look like much of a splash screen. Any idea why? What should I do?

For bonus points, does anyone know where to find an explanation for all series of events that occur in typical creation, usage, and destruction of forms? The above problem is probably because I don't understand what order things occur or where to hook into form events.


UPDATE Close, but not quite: looking for a little more advice. Here's the current code:

private SplashScreen splash = new SplashScreen();

private void RealForm_Load(object sender, EventArgs e)
{

    splash.Show();

    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler
         (worker_RunWorkerCompleted);
    worker.RunWorkerAsync();
    this.Visible = false;

}

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    splash.Close();
    this.Visible = true;
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    loadAndCheckDatabase();
}

Unfortunately, the this.Visible = false doesn't do anything, because it is automatically set to true in code that I don't control. So, to get around this, I put the this.Visible = false into the handler for the form's Shown event. However, as you can probably guess, you can still see the form for a split second... so this is not really a good solution.

Is there any way to wait on the worker thread while I'm still in the Load handler?

like image 946
JnBrymn Avatar asked Dec 17 '22 22:12

JnBrymn


1 Answers

You are displaying the splash screen and checking your database on the same thread. The thread can only do one thing at a time.

A quick and cheap way to fix this is to have loadAndCheckDatabase() call Application.DoEvents() periodically. However that's a cheap fix.

You really want to run loadAndCheckDatabase() on its own thread, a BackgroundWorker is a nice simple way to do this.

like image 67
Matt Greer Avatar answered Dec 30 '22 23:12

Matt Greer