LDNDeveloper

Andrew Pallant

Software & Web Developer


Donate To Support My Blog Donate if this post helped you. Coffee money is always welcomed!




DotNet Windows Form Image Transparency

Physical Link: DotNet Windows Form Image Transparency


Recently during a project I had a need to overlay an image on a windows form in order to indicate a status of inability.  This image had a semi-transparency quality as well as a full transparency background.  To my dismay, the semi-transparency rendered in full color and the full transparency background seemed to inherit the parent form, but not show the controls behind it as one would expect.

After sometime of researching the issue, I came to a determination that what I was trying to do could only be done in web development (HTML).  From my research I had assembled some ideas in how to make transparencies work.   I took ideas from several sources and came up with the following.

Step By Step ( see Sample Code )

1. Create a class that extends System.Windows.Forms.Control
2. Place code from sample cod
3. Compile Project
4. Add new control to the Form ( remember this is for a windows application )
5. Set Background Image

Sample Code


protected override CreateParams CreateParams
{
     // Make window transparent
     get
     {
          CreateParams cp = base.CreateParams;
          cp.ExStyle |= 0x20;  // WS_EX_TRANSPARENT return cp;
     }
}

protected override void OnPaintBackground(PaintEventArgs pevent)
{
// Do not paint the background
}

protected override void OnPaint(PaintEventArgs e)
{ 
     // Paint background image 
     if (BackgroundImage != null)
     {
          Bitmap bmp = new Bitmap(BackgroundImage);
          bmp.MakeTransparent(Color.White);
          e.Graphics.DrawImage(bmp, 0, 0, Width, Height);
     }
}

Note:  When you overlay an image – even transparent, you may see the controls behind, but you will not be able to access them.  This is true in both web and windows development.

The post DotNet Windows Form Image Transparency appeared first on LDNDeveloper.

Author:
Categories: Better Coding, C#, Deployment, DotNet


©2024 LdnDeveloper