How to make the background of a label transparent in c#

14,474

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:

enter image description here

Share:
14,474
Lakindu
Author by

Lakindu

Updated on June 05, 2022

Comments

  • Lakindu
    Lakindu almost 2 years

    I have form as in the image below.

    enter image description here

    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.

  • A. Niese
    A. Niese over 3 years
    I realize this is for .NET Framework, but in .NET Core 3.1 Winforms, this generates an out of memory exception on the .Clone line.