简体   繁体   中英

Setting a label background colour to transparent in WinForms make it ignore any images underneath it and displays the form background image instead

I'm working on a very image intensive application.

In this example, there is a Panel at the very back with a background image and a PictureBox ontop of that with a background image. When I add a label ontop of that and set the background colour to be transparent, the background colour displayed is of the Panel background image and it completely ignores the image that's in between the two. Am I doing something wrong?

That's how transparency works in Windows Forms. It's fake. A transparent control isn't actually transparent and allowing what's behind it to show through. Instead, it just draws a copy of its parent in its own background. If you want a PictureBox to show through a Label then the Label has to actually be a child of the PictureBox . The catch is that you cannot do that in the designer, so you have to add the Label to some other container and then move it to the PictureBox in code. I suggest that you place the Label in the exact location you want it in the designer, regardless of its parent container. You can then do this in the Load event handler of your form:

label1.Location = pictureBox1.PointToClient(label1.PointToScreen(Point.Empty));
label1.Parent = pictureBox1;

That code gets the location of the Label relative to the screen, then translates that to a Point relative to the PictureBox and assigns that to the Location of the Label . When the Label is added to the PictureBox , it appears at that location, so in the exact same location it was to start with, only inside the PictureBox .

Here's an extension method that does the same thing:

public static class ControlExtensions
{
    public static void SetParentWithSameScreenCoordinates(this Control source, Control parent)
    {
        source.Location = parent.PointToClient(source.PointToScreen(Point.Empty));
        source.Parent = parent;
    }
}

You can then do this in your Load event handler:

label1.SetParentWithSameScreenCoordinates(pictureBox1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM