Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the parent of a usercontrol prevents it from being transparent

I've created a simple user control which is manually created with something like

MyUserControl ctrl = new MyUserControl();

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.

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.

Basically if you do this

  • Create a form
  • Drop a button on it
  • In the click handler for the button you do the following

Example

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.

Thanks!

EDIT: 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.

like image 620
TheCodeJunkie Avatar asked Dec 17 '08 07:12

TheCodeJunkie


1 Answers

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.

like image 159
Rune Grimstad Avatar answered Oct 21 '22 23:10

Rune Grimstad