问题描述
我创建了一个简单的用户控件,它是用类似的东西手动创建的
I've created a simple user control which is manually created with something like
MyUserControl ctrl = new MyUserControl();
控件已被设计为具有 BackColor = Color.Transparent 并且工作正常,直到我将控件的 Parent 设置为一个窗体,此时它变为进入表单的颜色.
The control have been designed to have BackColor = Color.Transparent and that works fine, until I set the Parent of the control to a form at which time it turns into the color of the form.
可能听起来像是透明的,但它的作用是隐藏表单上存在的所有控件.我不能 100% 确定它的控件获得了纯色背景或当我连接它时发生的其他事情,这会阻止其他控件显示.
Might sound like its transparent but what it does is hide all the controls that exist on the form as well. I'm not 100% sure its the control that gets a solid background or something else thats happening when i hook it up, which prevents other controls from showing.
基本上如果你这样做
- 创建表单
- 在上面放一个按钮
- 在按钮的点击处理程序中执行以下操作
例子
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();
基本上我希望用户控件覆盖整个表单,同时在表单上显示底层控件(因此是透明背景).我不想将它添加到表单控件集合中,因为它并不真正属于表单,它只是显示在其他所有内容之上
Basically I want the usercontrol to overlay the entire form, while showing the underlaying controls on the form (hence the transparent background). I do not want to add it to the forms control collection because it doesn't really belong to the form, its just being shown ontop of everything else
我尝试做同样的事情,但没有设置父级,但是控件根本没有显示.
I tried doing the same, but without setting the parent, but then the control didnt show at all.
谢谢!
如果我覆盖用户控件中的 OnPaintBackground 方法并阻止绘制背景,那么它可以工作,但是这会与使用 DrawImage 在控件中绘制的 PNG 图像的透明部分混淆,这是有道理的.
If I override the OnPaintBackground method in the usercontrol and prevent the background from being painted then it works, however that messes up with the transparent parts of a PNG image im painting in the control using DrawImage, which makes sense.
推荐答案
Windows 窗体并不真正支持透明控件.
您可以通过覆盖控件的 CreateParams 属性并设置自定义样式(在 google 上查找)来解决此限制.
此外,您必须重写控件的绘制,以便不仅重绘您的控件,而且重绘父控件.原因是必须在控件绘制自身之前绘制背景.
最后你应该重写 OnPaintBackground 方法,就像你所做的那样,以确保没有背景被绘制.
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.
这篇关于设置用户控件的父级可防止其透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!