Run CMD
Run CMD

Reputation: 3035

Closing the splash screen from a different thread?

I'm using WindowsFormsApplicationBase to show a splash screen. Now, when the main form is created, and errors occur, a messagebox should be shown informing the user. However, the messagebox is displayed under the splash screen, so it's not visible. I need to close the splash screen so I can interact with the user.

The following code will give a cross-thread operation exception :

class SingleInstanceApplication : WindowsFormsApplicationBase
{
    private static SingleInstanceApplication instance;

    public static void CloseSplash()
    {
        if (instance.SplashScreen != null)
            instance.SplashScreen.Close();
    }
}

Error:

Cross-thread operation not valid: Control 'Splash' accessed from a thread 
other than the thread it was created on.

Is this even possible ??

Upvotes: 3

Views: 1999

Answers (2)

Otiel
Otiel

Reputation: 18743

If your splash screen form is named mySplashScreen:

mySplashScreen.Invoke(new MethodInvoker(delegate {
    mySplashScreen.Close();
    mySplashScreen.Dispose();
}));

Upvotes: 3

James Johnston
James Johnston

Reputation: 9492

You can't access user interface elements from a thread other than the one that created them. Commonly one can use Control.Invoke to access UI elements from other threads.

Upvotes: 2

Related Questions