Question

I want to set the Background color of my form to transparent. I know that this is possible by setting TransparencyKey, but this wont work for me because I have an image with different alpha values rendered on the form. I tried to overwrite the OnPaintBackground method but then I get a black background. Is there a better way to set the forms background transparency?

Was it helpful?

Solution

That cannot work, a transparent color lets the background shine through. But a form's background doesn't itself have a background. You'll see whatever the pixels were initialized to in the video adapter's frame buffer when the window was created. Which is normally white, it will be black on some machines if you used the Opacity or TransparencyKey properties.

To punch a hole through the window itself so you see whatever windows are behind it you must use a layered window. Where the video adapter itself combines the pixels in the frame buffer with the pixels of your window, stored in a separate overlay. The same kind of effect you see used on television with the weather man standing in front of the weather map, called color-keying.

Which is trivial to do, simply set the form's BackColor to the same value as the TransparencyKey property. Pick an "unusual" color that doesn't appear anywhere else in the window, Color.Fuchsia is an excellent fuchsed-up color.

OTHER TIPS

Don't set the TransparencyKey. Set the Opacity:

this.Opacity = 0.5d;

Note: This makes the whole window (semi-)transparent, including its borders and header! If you set it to 0.0d it will be completely invisible!

You still need to paint background for it to be transparent (or well you will see that black background).

protected override void OnPaintBackground(PaintEventArgs e)
{
    using (SolidBrush brush = new SolidBrush(this.TransparencyKey))
        e.Graphics.FillRectangle(brush, ClientRectangle);
}

Don't forget to set transparency key and backcolor

TransparencyKey = BackColor = Color.LavenderBlush; // to example

and user paint style.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top