public struct BlendFunction
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
public enum BlendOperation : byte
{
AC_SRC_OVER = 0x00
}
public enum BlendFlags : byte
{
Zero = 0x00
}
public enum SourceConstantAlpha : byte
{
Transparent = 0x00,
Opaque = 0xFF
}
public enum AlphaFormat : byte
{
AC_SRC_ALPHA = 0x01
}
[DllImport("coredll.dll")]
extern public static Int32 AlphaBlend(IntPtr hdcDest, Int32 xDest, Int32 yDest, Int32 cxDest, Int32 cyDest, IntPtr hdcSrc, Int32 xSrc, Int32 ySrc, Int32 cxSrc, Int32 cySrc, BlendFunction blendFunction);
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (backBuffer != null)
{
// We need a Graphics object on the buffer to get an HDC
using (Graphics gxBuffer = Graphics.FromImage(backBuffer))
{
// Since we nop'd OnPaintBackground, take care of it here
gxBuffer.Clear(this.BackColor);
// AlphaBlend takes two HDC's - one source and one destination. Here's the source.
using (Graphics gxSrc = Graphics.FromImage(displayImage))
{
IntPtr hdcDst = gxBuffer.GetHdc();
IntPtr hdcSrc = gxSrc.GetHdc();
BlendFunction blendFunction = new BlendFunction();
blendFunction.BlendOp = (byte)BlendOperation.AC_SRC_OVER; // Only supported blend operation
blendFunction.BlendFlags = (byte)BlendFlags.Zero; // Documentation says put 0 here
blendFunction.SourceConstantAlpha = transparencyValue; // Constant alpha factor
blendFunction.AlphaFormat = (byte)0; // Don't look for per pixel alpha
int left = this.Width / 2 - (displayImage.Width / 2); // Get x co-or based on bitmap width
int top = 100; // y co-or
AlphaBlend(hdcDst, left, top,
displayImage.Width, displayImage.Height,
hdcSrc, 0, 0,
displayImage.Width, displayImage.Height,
blendFunction);
gxBuffer.ReleaseHdc(hdcDst); // Required cleanup to GetHdc()
gxSrc.ReleaseHdc(hdcSrc); // Required cleanup to GetHdc()
}
}
// Put the final composed image on screen.
e.Graphics.DrawImage(backBuffer, 0, 0);
}
else
e.Graphics.Clear(this.BackColor);
}