1

I wanted my program to show a loading message while it checks if the program has connected to a device... but i get an error when i try to close the splashform using the code

SplashForm.CloseForm();

the actual splashform code is...

class SplashForm
{
    //Delegate for cross thread call to close
    private delegate void CloseDelegate();

    //The type of form to be displayed as the splash screen.
    private static SplashForm splashForm;

    static public void ShowSplashScreen()
    {
        // Make sure it is only launched once.

        if (splashForm != null)
            return;
        Thread thread = new Thread(new ThreadStart(SplashForm.ShowForm));
        thread.IsBackground = true;
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();           
    }

    static private void ShowForm()
    {
        splashForm = new SplashForm();
        Application.Run(splashForm);
    }

    static public void CloseForm()
    {
        splashForm.Invoke(new CloseDelegate(SplashForm.CloseFormInternal));
    }

    static private void CloseFormInternal()
    {
        splashForm.Close();
    }
...
}

in this code... I get a error message as "Object reference not set to an instance of an object" at the line

 splashForm.Invoke(new CloseDelegate(SplashForm.CloseFormInternal));

what is the reason and solution?

John Saunders
  • 157,405
  • 24
  • 229
  • 388
  • I am using the same splash form for other process also in the same program. It works there but doesn't work for this particular code where i check for device connect. – sabhrish balasubramanian Jun 22 '15 at 03:04

1 Answers1

0

The Object reference not set to an instance of an object message is the trademark of the NullReferenceException. Here, it means that your splashForm field is null.

Make sure that you have 1) called SplashForm.ShowSplashScreen() before you call SplashForm.CloseForm() and 2) consider calling thread.Join() in ShowSplashScreen() so you can be sure that by the time you leave that method, splashForm is not null.

James Ko
  • 25,479
  • 23
  • 92
  • 196