Search code examples
c#winformstransparency

Winforms transparent form issue


I am trying to draw a form that has a transparent background and a blurred dropshadow from a main body.

The way I did this is to use the form as the bounding box, then draw the actual form's body inside that with margin on the sides for the shadow to show. The shadow expands from behind the drawn body.

So, I have 1 form in which I draw inside. I want the form's background to be transparent so that only the drawn body and the shadow appears.

I have some problems with the shadow. The shadow is a bitmap in which I apply AForge's gaussian blur to create the shadow effect. The bitmap is placed behind the drawn body so that it appears as the shadow.

Here is the problem: The form's backcolor remains drawn where the shadow is. The shadow bitmap is transparent except for the blurred blacks.

I have tried setting backcolor to transparent, or a misc color and then transparencykey to the same color. results stays the same.

Picture of what I want to achieve: enter image description here

(light pink is not a part of the program, imagine it as the desktop)

Picture of what I am getting: enter image description here

(I am only drawing the shadow for this example, not the white body(which works fine), the form's background refuses to become transparent where the shadow exists..)

This is the code for creating the shadow's bitmap.

    private void _CreateShadow()
    {
        shadowImg = new Bitmap(m_ShadowRect.Width, m_ShadowRect.Height, PixelFormat.Format32bppArgb);
        Graphics g = Graphics.FromImage(shadowImg);
        int diameter = Math.Min(shadowImg.Width, shadowImg.Height);
        g.DrawEllipse(m_ShadowPen, m_ShadowWidth, m_ShadowWidth, m_BodyRect.Width - m_ShadowWidth, m_BodyRect.Height - m_ShadowWidth);
        filter.ApplyInPlace(shadowImg);
    }

    private void _DrawShadow(Graphics g)
    {
        g.DrawImage(shadowImg, m_ShadowRect.X, m_ShadowRect.Y);
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);

        _DrawShadow(pe.Graphics);
        _DrawBody(pe.Graphics);
    }

Please, any pointers?


Solution

  • Have a look at this file in a github repository, mainly the lines 123 - 131, 253 - 415. The code uses GDI+ methods to draw transparent bitmap that replaces the form background.

    You cannot draw anything transparent on a Form because all the methods (like OnPaint) use Format24bppRgb not Format32bppArgb, which is what you need.