My interests are in: - Microsoft Visual Studio .Net - Microsoft SQL Server. - Delphi. - ERP. - DNS, SOA, SAS, ... etc.

Wednesday, March 19, 2008

Transparent Windows Forms Controls

Transparent Windows Forms Controls: "Creating transparent Windows Forms controls.

The transparency feature of the Windows Forms control leaves much to be desired and is a blatant fudge. The control is not really transparent, it just pretends to be by looking at the background of it's parent control and copying the appropriate portion of the image or background onto it's own surface during the OnPaintBackground method.

This means that a 'transparent' control placed on top of another on the same parent will in fact obscure the other child controls. Figure 1 shows this effect in action.


Figure1: A supposedly transparent Panel

The panel control to the right of the form obscures the PictureBox control and shows only the background of the parent.

In order to make a truly transparent control we need to do a couple of things. Firstly, it's necessary to change the behaviour of the window by giving it a WS_EX_TRANSPARENT style. This is accomplished by overriding the CreateParams property so that the correct window style is included when the control is instantiated. The listing below shows this property override.

protected override CreateParams CreateParams
{
get
{
CreateParams cp=base.CreateParams;
cp.ExStyle|=0x00000020; //WS_EX_TRANSPARENT
return cp;
}
}

The second thing we need to do is to invalidate the parent of the control, not the control itself, whenever we need to update the graphics. This ensures that whatever is behind the control gets painted before we need to do our own graphics output. To do this, a routine such as that shown in the following listing is needed.

protected void InvalidateEx()
{
if(Parent==null)
return;
Rectangle rc"

No comments: