Search code examples
c#imageformspictureboxsplash-screen

Picture Box doesn't show image


I have a form project in Vs2010. This is my scenario: I created a form that I want to use like a splash screen, without borders. Inside I have a picture box big like the form. I set the image importing it and in designer i can see it. But when I call the splashscreen form from another form and I show It, I can see only the picture box borders, but doesn't load the image.

Update

I load splashScreen in BmForm_Load (other form):

SplashScreen ss = new SplashScreen();
ss.TopMost = true;
ss.Show();
//Prepare bmForm....
ss.Close();

And this is the designer code snippet for the picture box in splash screen form:

this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.ImageLocation = "";
this.pictureBox1.InitialImage = null;
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(256, 256);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
this.pictureBox1.WaitOnLoad = true;

Update 2

If I doesn't close splashScreen form before other form load end, the image is shown after this!

Question

Somebody knows why isn't the picture showed?


Solution

  • What the problem seems to be is that the preparation of your BmForm is locking down the main UI thread that is trying to load the splash image as well as process the commands to prepare the BmForm.
    To counter this, load the splash form in its own thread and close the thread/form when done loading.

    Example of the code:

    Inside your BmForm_Load

    Thread splashThread = new Thread(ShowSplash);
    splashThread.Start();
    
    // Initialize bmForm
    
    splashThread.Abort();
    // This is just to ensure that the form gets its focus back, can be left out.
    bmForm.Focus();
    

    The method to show the splash screen

    private void ShowSplash()
    {
      SplashScreen splashScreen = null;
      try
      {
        splashScreen = new SplashScreen();
        splashScreen.TopMost = true;
        // Use ShowDialog() here because the form doesn't show when using Show()
        splashScreen.ShowDialog();
      }
      catch (ThreadAbortException)
      {
        if (splashScreen != null)
        {
          splashScreen.Close();
        }
      }
    }
    

    You might need to add the using System.Threading; to your class and add some extra error handling to the BmForm_Load event in case errors occur, so that you can clean up the splashThread.

    You can read more about threading here