How to make the background of a label transparent

2019-05-27 05:56发布

问题:

This question already has an answer here:

  • Reasons for why a WinForms label does not want to be transparent? 11 answers

I have form as in the image below.

I want to see label1 and label3 through label2. (I just want to see only the border of the label2). I have changed the BackColor in label2 to Transparent. But the result is same like the above picture.

回答1:

In Windows Forms you can't do this directly. You can work with BackgroundImage.

Try this:

void TransparetBackground(Control C)
{
    C.Visible = false;

    C.Refresh();
    Application.DoEvents();

    Rectangle screenRectangle = RectangleToScreen(this.ClientRectangle);
    int titleHeight = screenRectangle.Top - this.Top;
    int Right = screenRectangle.Left - this.Left;

    Bitmap bmp = new Bitmap(this.Width, this.Height);
    this.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height));
    Bitmap bmpImage = new Bitmap(bmp);
    bmp = bmpImage.Clone(new Rectangle(C.Location.X+Right, C.Location.Y + titleHeight, C.Width, C.Height), bmpImage.PixelFormat);
    C.BackgroundImage = bmp;

    C.Visible = true;
}

and in Form_Load:

private void Form1_Load(object sender, EventArgs e)
{
    TransparetBackground(label2);
}

and you can see this result:



标签: c# label labels