Click here to Skip to main content
15,887,381 members
Articles / Programming Languages / C#

Per Pixel Alpha Blend in C#

Rate me:
Please Sign up or sign in to vote.
4.72/5 (73 votes)
3 Jun 20041 min read 602.2K   19.4K   191   115
Demonstrates how to create per pixel alpha blending Windows

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 new ways of doing 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

31st May, 2004

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

12th February, 2002

  • Initial version

Do you have any question or comment? Please leave a note below.

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.


Written By
Web Developer
Portugal Portugal
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralExactly what I was looking for. Thanks. Pin
mlavenne18-Aug-08 11:36
mlavenne18-Aug-08 11:36 
QuestionGreat but can I use the function also for a control? Pin
it-bergmann14-Feb-08 1:24
it-bergmann14-Feb-08 1:24 
AnswerRe: Great but can I use the function also for a control? Pin
sebastianlaskawiec19-May-09 4:49
sebastianlaskawiec19-May-09 4:49 
Generalcool Pin
radioman.lt12-Dec-07 22:20
radioman.lt12-Dec-07 22:20 
Questionwhy doing win32 with c#? Pin
bkaratte11-Dec-07 20:46
bkaratte11-Dec-07 20:46 
AnswerRe: why doing win32 with c#? Pin
tic8410-Jun-08 13:12
tic8410-Jun-08 13:12 
GeneralVB.Net Pin
dawmail33324-Aug-07 22:47
dawmail33324-Aug-07 22:47 
GeneralRe: VB.Net Pin
Dj Den4ik11-Feb-08 23:05
Dj Den4ik11-Feb-08 23:05 
Class:
<br />
Imports System<br />
Imports System.Drawing<br />
Imports System.Drawing.Imaging<br />
Imports System.Windows.Forms<br />
Imports System.Runtime.InteropServices<br />
'Translation from C# by Dj Den4ik<br />
Public Class PerPixelAlphaForm<br />
    'Implements Windows.Forms.IWin32Window<br />
<br />
    Public Structure ARGB<br />
        Public Blue As Byte<br />
        Public Green As Byte<br />
        Public Red As Byte<br />
        Public Alpha As Byte<br />
    End Structure<br />
<br />
    Public Structure BLENDFUNCTION<br />
        Public BlendOp As Byte<br />
        Public BlendFlags As Byte<br />
        Public SourceConstantAlpha As Byte<br />
        Public AlphaFormat As Byte<br />
    End Structure<br />
<br />
    Public Const ULW_COLORKEY As Int32 = &H1<br />
    Public Const ULW_ALPHA As Int32 = &H2<br />
    Public Const ULW_OPAQUE As Int32 = &H4<br />
<br />
    Public Const AC_SRC_OVER As Byte = &H0<br />
    Public Const AC_SRC_ALPHA As Byte = &H1<br />
<br />
    Public Declare Function UpdateLayeredWindow Lib "user32" Alias "UpdateLayeredWindow" (ByVal hwnd As IntPtr, ByVal hdcDst As IntPtr, ByRef pptDst As Point, ByRef psize As Size, ByVal hdcSrc As IntPtr, ByRef pprSrc As Point, ByVal crKey As Int32, ByRef pblend As BLENDFUNCTION, ByVal dwFlags As Int32) As Boolean<br />
    Public Declare Function GetDC Lib "user32" Alias "GetDC" (ByVal hWnd As IntPtr) As IntPtr<br />
    Public Declare Function ReleaseDC Lib "user32" Alias "ReleaseDC" (ByVal hWnd As IntPtr, ByVal hDC As IntPtr) As Integer<br />
    Public Declare Function CreateCompatibleDC Lib "gdi32.dll" Alias "CreateCompatibleDC" (ByVal hDC As IntPtr) As IntPtr<br />
    Public Declare Function DeleteDC Lib "gdi32.dll" Alias "DeleteDC" (ByVal hDC As IntPtr) As Boolean<br />
    Public Declare Function SelectObject Lib "gdi32.dll" Alias "SelectObject" (ByVal hDC As IntPtr, ByVal hObject As IntPtr) As IntPtr<br />
    Public Declare Function DeleteObject Lib "gdi32.dll" Alias "DeleteObject" (ByVal hObject As IntPtr) As Boolean<br />
<br />
    Public Sub SetBitmap(ByVal bitmap As Bitmap, ByVal opacity As Byte, ByVal frm As Form)<br />
        If bitmap.PixelFormat <> PixelFormat.Format32bppArgb Then Throw New ApplicationException("The bitmap must be 32ppp with alpha-channel.")<br />
<br />
        ' The ideia of this is very simple,<br />
        ' 1. Create a compatible DC with screen;<br />
        ' 2. Select the bitmap with 32bpp with alpha-channel in the compatible DC;<br />
        ' 3. Call the UpdateLayeredWindow.<br />
<br />
        Dim screenDc As IntPtr = GetDC(IntPtr.Zero)<br />
        Dim memDc As IntPtr = CreateCompatibleDC(screenDc)<br />
        Dim hBitmap As IntPtr = IntPtr.Zero<br />
        Dim oldBitmap As IntPtr = IntPtr.Zero<br />
<br />
        Try<br />
            hBitmap = bitmap.GetHbitmap(Color.FromArgb(0))  ' grab a GDI handle from this GDI+ bitmap<br />
            oldBitmap = SelectObject(memDc, hBitmap)<br />
            Dim size As New Size(bitmap.Width, bitmap.Height)<br />
            Dim pointSource As New Point(0, 0)<br />
            Dim topPos As New Point(frm.Left, frm.Top)<br />
            Dim blend As New BLENDFUNCTION<br />
            blend.BlendOp = AC_SRC_OVER<br />
            blend.BlendFlags = 0<br />
            blend.SourceConstantAlpha = opacity<br />
            blend.AlphaFormat = AC_SRC_ALPHA<br />
            UpdateLayeredWindow(frm.Handle, screenDc, topPos, size, memDc, pointSource, 0, blend, ULW_ALPHA)<br />
        Finally<br />
            ReleaseDC(IntPtr.Zero, screenDc)<br />
            If hBitmap <> IntPtr.Zero Then<br />
                SelectObject(memDc, oldBitmap)<br />
                DeleteObject(hBitmap)<br />
            End If<br />
            DeleteDC(memDc)<br />
<br />
        End Try<br />
    End Sub<br />


Form:
<br />
    Dim ppaf As New PerPixelAlphaForm<br />
    Dim bmp As New Bitmap("D:\Audio\FL Studio 7\Artwork\FL Studio Producer Edition\Title_.png")<br />
<br />
    Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams<br />
        Get<br />
            Dim SecPerm As New Security.Permissions.SecurityPermission(Security.Permissions.PermissionState.Unrestricted)<br />
            SecPerm.Demand()<br />
<br />
            ' Extend the CreateParams property of the Button class.<br />
            Dim cp As System.Windows.Forms.CreateParams = MyBase.CreateParams<br />
            ' Update the button Style.<br />
            cp.ExStyle = &H80000<br />
<br />
            Return cp<br />
        End Get<br />
    End Property<br />
<br />
    Private Sub frmTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load<br />
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None<br />
        Me.TopMost = True<br />
        For Each ctrl As Control In Me.Controls<br />
            ctrl.DrawToBitmap(bmp, ctrl.Bounds)<br />
        Next<br />
        Me.Region = New Region()<br />
        ppaf.SetBitmap(bmp, 240, Me)<br />
    End Sub<br />
<br />
<br />
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)<br />
<br />
        Const WM_MOUSEMOVE As Int32 = &H200<br />
        Const WM_NCLBUTTONDOWN As Int32 = &HA1<br />
        Const HTCAPTION As Int32 = 2<br />
<br />
        '// ????????????? WM_MOUSEMOVE <br />
        If m.Msg = WM_MOUSEMOVE Then<br />
<br />
            '// ???????? ReleaseCapture <br />
            MyBase.Capture = False<br />
<br />
            '// ??????? ???? ????????? <br />
            Dim message As New Message<br />
            With message<br />
                .HWnd = Me.Handle<br />
                .Msg = WM_NCLBUTTONDOWN<br />
                .WParam = HTCAPTION<br />
                .LParam = 0&<br />
            End With<br />
<br />
            '// ?????????? ???? ????????? ???? <br />
            MyBase.WndProc(message)<br />
        End If<br />
<br />
        MyBase.WndProc(m)<br />
<br />
    End Sub<br />

Smile | :)
GeneralRe: VB.Net Pin
Jason Newland25-Apr-12 19:31
Jason Newland25-Apr-12 19:31 
GeneralRe: VB.Net Pin
Jason Newland25-Apr-12 19:33
Jason Newland25-Apr-12 19:33 
GeneralGreat!!!!!!!!!!!!! Pin
shp-coding9-Aug-07 7:44
shp-coding9-Aug-07 7:44 
GeneralWay to add some controls Pin
ihess30-Jul-07 4:17
ihess30-Jul-07 4:17 
GeneralRe: Way to add some controls [modified] Pin
Sp3cial24-Aug-08 8:12
Sp3cial24-Aug-08 8:12 
GeneralRe: Way to add some controls [modified] Pin
LatencyXXX23-Jan-11 23:21
LatencyXXX23-Jan-11 23:21 
GeneralHelp Pin
Gihan Liyanage28-May-07 20:15
professionalGihan Liyanage28-May-07 20:15 
GeneralImage problem Pin
darb220-Apr-07 12:57
darb220-Apr-07 12:57 
GeneralRe: Image problem Pin
Daryl Fish15-Jan-08 14:58
Daryl Fish15-Jan-08 14:58 
GeneralProblem when changing the form parent to desktop with dual-monitoring [modified] Pin
Pim-Pom7-Oct-06 1:59
Pim-Pom7-Oct-06 1:59 
GeneralNice example, but... Pin
moebiusproject12-Sep-06 9:35
moebiusproject12-Sep-06 9:35 
GeneralRe: Nice example, but... Pin
Tung Nguyen15-Apr-07 17:37
Tung Nguyen15-Apr-07 17:37 
GeneralRe: Nice example, but... Pin
tic8410-Jun-08 13:14
tic8410-Jun-08 13:14 
GeneralProblem in design mode Pin
Member 303363812-Jul-06 19:09
Member 303363812-Jul-06 19:09 
GeneralRe: Problem in design mode Pin
ODaniell3-Aug-06 0:52
ODaniell3-Aug-06 0:52 
GeneralRe: Problem in design mode Pin
sebastianlaskawiec19-May-09 4:50
sebastianlaskawiec19-May-09 4:50 
QuestionHow Can I Add Controls? Pin
ranzige2-Dec-05 16:32
ranzige2-Dec-05 16:32 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.