如何在C#中使UserControls BackColor透明化?

我在Windows窗体用户控件中创建了一个简单的操作员(由单选按钮和三个标签以及一个进度条组成)。

我将新用户控件的背景颜色设置为透明,这样当我将其拖到我的表单上时,它会与表单上的其他颜色和绘图混合。 我没有得到我想要实现的目标。

这是图片:

在此处输入图像描述

UserControl已经支持此function,其ControlStyles.SupportsTransparentBackColor样式标志已经打开。 您所要做的就是将BackColor属性设置为Color.Transparent。

接下来要记住这个透明度是模拟的,它是通过要求控件的Parent绘制自己来生成背景来完成的。 所以重要的是你正确设置了Parent。 如果父级不是容器控件,那么这有点棘手。 像PictureBox一样。 设计师将表格作为父母,因此您将看到表格的背景,而不是图片框。 您需要在代码中修复它,编辑表单构造函数并使其看起来类似于:

var pos = this.PointToScreen(userControl11.Location); userControl11.Parent = pictureBox1; userControl11.Location = pictureBox1.PointToClient(pos); 

在构造函数中设置控件样式以支持透明背景颜色

 SetStyle(ControlStyles.SupportsTransparentBackColor, true); 

然后将Background设置为transperent color

 this.BackColor = Color.Transparent; 

来自MSDN

这里描述了一种更复杂的方法(可能还有一种方法) – 包含CreateParamsOnPaint覆盖。

为什么这些东西? UserControl类具有属性Region。 将其设置为您喜欢的形状,无需进行其他调整。

 public partial class TranspBackground : UserControl { public TranspBackground() { InitializeComponent(); } GraphicsPath GrPath { get { GraphicsPath grPath = new GraphicsPath(); grPath.AddEllipse(this.ClientRectangle); return grPath; } } protected override void OnPaint(PaintEventArgs e) { // set the region property to the desired path like this this.Region = new System.Drawing.Region(GrPath); // other drawing goes here e.Graphics.FillEllipse(new SolidBrush(ForeColor), ClientRectangle); } } 

结果如下图所示:

在此处输入图像描述 没有低级代码,没有调整,简单和干净。 但是有一个问题,但在大多数情况下,它可以不被检测到,边缘不平滑,抗锯齿也无济于事。 但解决方法相当容易。 事实上,比所有复杂的背景处理要容易得多..