Click here to Skip to main content
Click here to Skip to main content

Per Pixel Alpha Blend in C#

By , 3 Jun 2004
 

Preview of the per pixel alpha blend effect

Preview of the per pixel alpha blend effect

Introduction

This is a port of my other article from C++/MFC to C#/Windows Forms. The concept of creating a per-pixel-alpha blending window remains the same, the GDI function UpdateLayeredWindow.

What changed

  • Image loading is handled by GDI+ classes (System.Drawing namespace).
  • No need to pre-multiply the rgb channels with the alpha channel.
  • No more support for PSP files. PNG file are the best choice.

Usage

To use this code you need to include PerPixelAlphaForm.cs file in your project, create a class that inherits from PerPixelAlphaForm, load a bitmap using System.DrawingImage.FromFile static method and then call the PerPixelAlphaForm.SetBitmap method.

The example source code is inside the main.cs file. In the source code you will also find the new ways of doing the old things, like, handling dropped files from windows explorer.

Installing & Building

  1. Download and extract the source code of this article;
  2. To build, run the build.bat file from command prompt;
  3. Now, run the bin\main.exe and enjoy!

Changelog

31 May 2004

  • Fix clipping problems by creating the form without borders.
  • Move PerPixelAlphaForm class to PerPixelAlphaForm.cs file.

12 Feb 2002

  • Initial version.

Do you have any question or comment? Contact me!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Rui Lopes
Web Developer
Portugal Portugal
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionDouble Click problemmemberMember 815980915 Feb '13 - 10:52 
There is a problem when double click on alpha form. How can I solve it?
QuestionquestionmemberMember 976512017 Jan '13 - 8:32 
this is great! question: is there any way to make the overlay unclickable / not lose window focus of other programs if clicked?
GeneralMy vote of 5membervasanth300820 Nov '12 - 3:39 
Really a code i searched so far
QuestionProjectmemberEGHSanc27 Aug '12 - 3:48 
Thank you so much for this great article, but can you give me the project files? *csproj
QuestionClick eventmembermybigfatcatNL10 Aug '12 - 7:37 
Do you know how can i add a onclick event to the forms?Confused | :confused:
 
5/5 stars
GeneralMy vote of 4memberYawness13 May '12 - 20:51 
My vote of 4
GeneralMy vote of 5membermanoj kumar choubey18 Feb '12 - 3:29 
Nice
QuestionDrawing other stuff on?memberRohit Dubey from Hyderabad22 Jan '12 - 20:10 
Great job, it looks great! I was just wondering, how would I go about drawing shapes such as rectangles, ellipses and lines using GDI? I've tried creating a Graphics object with the Graphics.FromHdc method but when I try drawing something, it doesn't appear.
AnswerRe: Drawing other stuff on?memberRohit Dubey from Hyderabad22 Jan '12 - 20:14 
Never mind, I created a new bitmap and just drew onto it using Graphics.FromImage.
QuestionImage Sizememberdownsource6 Jan '12 - 0:51 
Hi, I wanted to use this code inside an MDI Container to darken the area around an dialog box (like Vista/7 does), but I can't really figure out how to do it.
When I try to make the image bigger than it's 'physical' size is, it just isn't displayed. Do you know how to solve this prob? I haven't found a solution so far.
Questionform controls TooltipmemberAntonio Pelleriti14 Dec '11 - 21:45 
Is there a way to display a tooltip for a control on the form?
 
the controls are displayed with your code:
 
Bitmap temp_bmp = new Bitmap(bitmap);
foreach (Control ctrl in this.Controls)
{
                    ctrl.DrawToBitmap(temp_bmp, ctrl.Bounds);
}

SuggestionCan you give use link of whole projectmemberMember 793369229 Jun '11 - 6:16 
Can you give use link of whole project with *.csproj or sln files,, b`coz it is difficult to create and load any form single file in VS 2005
GeneralMy vote of 2memberjoin sam lee25 Jul '10 - 22:51 
good
GeneralMy vote of 5memberKPEBEDKO19 Jul '10 - 2:53 
Great work!
GeneralThank you!memberEduard Keilholz2 Jul '10 - 2:41 
Used your code in my project, works flawless
 
Thank you!
.: I love it when a plan comes together :.
http://www.zonderpunt.nl

AnswerFinding a working image [SOLVED]memberelmernite17 Dec '09 - 5:25 
I made an image in the GIMP and saved it as a transparent png but it isn't working?
I'm getting the "The bitmap must be 32ppp with alpha-channel." exception. How do I check to this? I've never hear of "ppp" before.
 
-Elmernite
 
After editing around I found that I need to set "Save color values from transparent pixels" With that checked it works.
 
modified on Thursday, December 17, 2009 11:37 AM

GeneralRe: Finding a working image [SOLVED]memberGee.1 Mar '10 - 12:13 
I think the author mis-typed bpp (Bits-Per-Pixel)...
Gee

GeneralAnchor Controls doesnt work if using Per Pixel Alpha Blendmemberdamon8812 Dec '09 - 21:03 
I noticed that anchoring doesnt work if you use PPAB,
 
I think its because of the way controls are drawn to bitmap, anchor offsets are not taken into account, Can you help me fix this ?
Generalsmall questionmembernirishere4 Sep '09 - 15:46 
Is it possible to draw on that image ? say a rectangle ?
What is the way to access the pixel buffer and modify it ? rgba-wise
Would it take a double buffer for the drawing to avoid the flickering ?
tx
GeneralAdd ControlsmemberGottdrak9919 Nov '08 - 12:23 
Here is a workaround:
 
...
 
class PerPixelAlphaForm : Form
{
  <code>Timer _RefreshFormTimer = new Timer();</code>
 
  public AlphaForm()
  {
    // This form should not have a border or else Windows will clip it.
    FormBorderStyle = FormBorderStyle.None;
 
    <code>_RefreshFormTimer.Interval = 10;
    _RefreshFormTimer.Tick += new EventHandler(RefreshFormTimer_Tick);
    _RefreshFormTimer.Enabled = true;</code>
  }
 
  <code>private Bitmap _FormBitmap;
  private byte _FormOpacity;
  private void RefreshFormTimer_Tick(object sender, EventArgs e)
  {
    if (_FormBitmap != null)
      SetBitmap(_FormBitmap, _FormOpacity);
  }</code>
 
  /// <para>Changes the current bitmap.</para>
  public void SetBitmap(Bitmap bitmap)
  {
    SetBitmap(bitmap, 255);
  }
 
...
 
...
	/// <para>Changes the current bitmap with a custom opacity level.  Here is where all happens!</para>
	public void SetBitmap(Bitmap bitmap, byte opacity)
	{
		if (bitmap.PixelFormat != PixelFormat.Format32bppArgb)
			throw new ApplicationException("The bitmap must be 32ppp with alpha-channel.");
 
    <code>_FormBitmap = bitmap;
    _FormOpacity = opacity;</code>
 
		// The ideia of this is very simple,
		// 1. Create a compatible DC with screen;
		// 2. Select the bitmap with 32bpp with alpha-channel in the compatible DC;
		// 3. Call the UpdateLayeredWindow.
 
		IntPtr screenDc = Win32.GetDC(IntPtr.Zero);
		IntPtr memDc = Win32.CreateCompatibleDC(screenDc);
		IntPtr hBitmap = IntPtr.Zero;
		IntPtr oldBitmap = IntPtr.Zero;
 
		try {
			<code>
                        foreach (Control ctrl in this.Controls)
                          ctrl.DrawToBitmap(bitmap, ctrl.Bounds);
</code>
                        hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));  // grab a GDI handle from this GDI+ bitmap
 
                        oldBitmap = Win32.SelectObject(memDc, hBitmap);
 
			Win32.Size size = new Win32.Size(bitmap.Width, bitmap.Height);
			Win32.Point pointSource = new Win32.Point(0, 0);
			Win32.Point topPos = new Win32.Point(Left, Top);
			Win32.BLENDFUNCTION blend = new Win32.BLENDFUNCTION();
...

 
Gottdrak99
 
modified on Thursday, November 27, 2008 3:22 AM

GeneralRe: Add Controlsmembercolche25 Feb '09 - 19:52 
fantastic! exactly what i was looking for...
 
Small note: I also had to wrap a .Visible check around the .DrawToBitmap method to meet my requirements.
 
foreach (Control ctrl in this.Controls) {
if (ctrl.Visible) {

ctrl.DrawToBitmap(bitmap, ctrl.Bounds);
}
}

GeneralRe: Add Controlsmemberrbrender9 Mar '09 - 17:44 
With this solution (timer) how can you show a blinking caret in a textbox?
GeneralRe: Add ControlsmemberMarko Padjen31 Mar '09 - 13:39 
Great addition!
 
One could also add in front of
_FormBitmap = bitmap;
to do that only if
_FormBitmap
is null.
Thatway, if you change for example Text on Label with transparent background, it won't be mixed.
GeneralRe: Add ControlsmemberLatencyXXX24 Mar '12 - 21:36 
This is not really a workaround. You are just rastering the controls to the background image. There is no independent relationship for any sort of a control. You are relying on the alpha channel to be blended based on its opaqueness rather than the opacity in conjunction with properties of a control itself.
 
I think there needs to be some different means to achieve a more practical solution. Have your alpha form as background and a separate transparent form with all your controls sync'd with the movement of the underlying form. Your going to have to layer the forms accordingly and preserve the ordering amongst other open windows.
 
I just can't believe they still haven't put anything for this in GDI+ or WF in VS11b and expect us to interop with Win32 which doesn't make things easy for many. You do realize that even the resources can't even be imported correctly without losing the alpha channel? Still no fix, M$ cherry picks every single thing known to man and it's not that hard to fix simple issues.
 
Good idea and I like the button images even though they arn't actual buttons or controls. Let us know if you get a fix or update/thread/link that shows us your new research, otherwise now might be a good time to switch to WPF since beta x11/12 is not showing any easy way to do what we really want in WF.
 
Meanwhile, take a look at this recommendation: Here which then leads to the CodeProject found There
-Latency

GeneralExactly what I was looking for. Thanks.membermlavenne18 Aug '08 - 11:36 
Great work.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 4 Jun 2004
Article Copyright 2002 by Rui Lopes
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid