views:

2266

answers:

1

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.

+2  A: 

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.

Rune Grimstad
Do you mean I should use the WS_CLIPCHILDREN flag when creating the control window?
TheCodeJunkie
No I think you mean WS_EX_TRANSPARENT
TheCodeJunkie
I just looked it up. you should OR the ExStyle property of the CreateParams objects with EX_TRANSPARENT (0x00000020)
Rune Grimstad