Monday, January 31, 2011

PictureBox with transparent overlay picture (C#)

Working yesterday on my remote control application that takes screenshots from a machine running XBMC I wanted to provide a better experience for the user by providing a “loading, please wait” transparent overlay image on top of the old screenshot image until new one comes in. Swimming through a lot of either complicated (Graphics.DrawImage in onPaint) or useless suggestions, I found one close to what I had in mind but didn’t give much attention to initially - using two PictureBox controls on top of each other, one for the main image and one for the overlay.

The trick is to change the background colour for the overlay picturebox to transparent and also change its parent. On top of that, if the main PictureBox is not in the top left corner and you want the overlay image to be centered, you also need to change the location of the overlay PictureBox relative to the new parent, otherwise it keeps the originally design margins.

In my case:
  • pictureBoxMain – displays the main image, image size mode Zoom;
  • pictureBoxOverlay – displays the “wait” transparent image, same size and anchoring, image size mode Center;
private void Form1_Load(object sender, EventArgs e)
{
  // Transparent background...  
  pictureBoxOverlay.BackColor = Color.Transparent;

  // Change parent for overlay PictureBox...
  pictureBoxOverlay.Parent    = pictureBoxMain;

  // Change overlay PictureBox position in new parent...
  pictureBoxOverlay.Location  = new Point(0, 0);
}


7 comments :

  1. it gives me an error when i set the parent :

    pictureBox2.Parent = pictureBox1;

    ReplyDelete
  2. Here is a sample project.
    http://www.2shared.com/file/7ObBjOec/WindowsFormsApplication1.html?

    ReplyDelete
  3. I want to do this for a Windows Mobile application, this is the error "Value does not fall within the expected range."

    pictureBox2.Parent = pictureBox1;

    ReplyDelete
  4. Sorry, my solution is for a desktop application. What's Windows Mobile using .Net Compact Framework? - maybe check this post: http://christian-helle.blogspot.com/2008/01/transparent-controls-in-netcf.html

    ReplyDelete
  5. If my PictureBox must overlay more than 1 other PictureBox? How can I do, I can't set the parent! Please I'm becoming crazy >.<

    ReplyDelete
  6. You could try cascading them, as in:

    private void Form1_Load(object sender, EventArgs e)
    {
    // Transparent background...
    pictureBoxOverlay.BackColor = Color.Transparent;

    // Change parent for overlay PictureBox...
    pictureBoxOverlay1.Parent = pictureBoxMain;

    // Change overlay picture 1 position in new parent...
    pictureBoxOverlay1.Location = new Point(0, 0);

    // Change parent for overlay picture 2...
    pictureBoxOverlay2.Parent = pictureBoxOverlay1;

    // Change overlay picture 2 position in new parent...
    pictureBoxOverlay2.Location = new Point(0, 0);

    }

    ReplyDelete