Transparent control over PictureBox

后端 未结 7 1980
遥遥无期
遥遥无期 2020-11-22 14:21

In my C# Form I have a Label that displays a download percentage in the download event:

  this.lblprg.Text = overallpercent.ToString(\"#0\") + \"%\";
         


        
7条回答
  •  孤城傲影
    2020-11-22 14:54

    The Label control supports transparency well. It is just that the designer won't let you place the label correctly. The PictureBox control is not a container control so the Form becomes the parent of the label. So you see the form's background.

    It is easy to fix by adding a bit of code to the form constructor. You'll need to change the label's Parent property and recalculate it's Location since it is now relative to the picture box instead of the form. Like this:

        public Form1() {
            InitializeComponent();
            var pos = this.PointToScreen(label1.Location);
            pos = pictureBox1.PointToClient(pos);
            label1.Parent = pictureBox1;
            label1.Location = pos;
            label1.BackColor = Color.Transparent;
        }
    

    Looks like this at runtime:

    enter image description here


    Another approach is to solve the design-time problem. That just takes an attribute. Add a reference to System.Design and add a class to your project, paste this code:

    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Windows.Forms.Design;    // Add reference to System.Design
    
    [Designer(typeof(ParentControlDesigner))]
    class PictureContainer : PictureBox {}
    

提交回复
热议问题