5

我创建了一个简单的用户控件,它是手动创建的,例如

MyUserControl ctrl = new MyUserControl();

该控件被设计为具有BackColor = Color.Transparent并且工作正常,直到我将控件的Parent设置为一个窗体,此时它变成窗体的颜色。

可能听起来像是透明的,但它的作用是隐藏表单上存在的所有控件。我不是 100% 确定它的控件获得了纯色背景或当我连接它时发生的其他事情,这会阻止其他控件显示。

基本上如果你这样做

  • 创建表单
  • 在上面放一个按钮
  • 在按钮的单击处理程序中,您执行以下操作

例子

MyUserControl ctrl = new MyUserControl();
ctrl.Parent = this;
ctrl.BackColor = Color.Transparent;
ctrl.Size = this.Parent.ClientRectangle.Size;
ctrl.Location = this.Parent.ClientRectangle.Location;
ctrl.BringToFront();
ctrl.Show();

基本上我希望用户控件覆盖整个表单,同时在表单上显示底层控件(因此是透明背景)。我不想将它添加到表单控件集合中,因为它并不真正属于表单,它只是显示在其他所有内容之上

我尝试做同样的事情,但没有设置父级,但是控件根本没有显示。

谢谢!

编辑:如果我覆盖用户控件中的 OnPaintBackground 方法并阻止绘制背景,那么它可以工作,但是这会与使用 DrawImage 在控件中绘制的 PNG 图像的透明部分混淆,这是有道理的。

4

1 回答 1

6

Windows Forms doesn't really support transparent controls.
You can work around this limitation by overriding the CreateParams property of the control and setting a custom style (look it up on google).
Further you have to override the painting of your control so that not only your control but also the parent control is redrawn. The reason is that the background must be painted before your control paints itself.
Finally you should override the OnPaintBackground method, as you have done, to make sure no background is painted.

Quite clumsy, and not perfect, but it should work.

于 2008-12-17T08:15:23.230 回答