/// <summary> /// Sets the bitmap of this layered window. /// </summary> /// <param name="bitmap">The bitmap.</param> public void SetBitmap(Bitmap bitmap) { //Test if the bitmap is compatible if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) { throw new ApplicationException("The bitmap must be 32bpp with alpha-channel."); } //Get the device contexts IntPtr screenDc = NativeMethods.GetDC(IntPtr.Zero); IntPtr memDc = NativeMethods.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr hOldBitmap = IntPtr.Zero; try { //Get handle to the new bitmap and select it into the current device context hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); hOldBitmap = NativeMethods.SelectObject(memDc, hBitmap); //Set parameters for layered window update NativeStructs.SIZE newSize = new NativeStructs.SIZE(bitmap.Width, bitmap.Height); NativeStructs.POINT sourceLocation = new NativeStructs.POINT(0, 0); NativeStructs.POINT newLocation = new NativeStructs.POINT(this.Left, this.Top); NativeStructs.BLENDFUNCTION blend = new NativeStructs.BLENDFUNCTION(); blend.BlendOp = NativeConstants.AC_SRC_OVER; blend.BlendFlags = 0; blend.SourceConstantAlpha = 255; blend.AlphaFormat = NativeConstants.AC_SRC_ALPHA; //Update the window NativeMethods.UpdateLayeredWindow(this.Handle, screenDc, ref newLocation, ref newSize, memDc, ref sourceLocation, 0, ref blend, NativeConstants.ULW_ALPHA); } finally { //Release the device context NativeMethods.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { NativeMethods.SelectObject(memDc, hOldBitmap); NativeMethods.DeleteObject(hBitmap); } //Delete the device context NativeMethods.DeleteDC(memDc); } }
public void SetBitmap(Bitmap bitmap, byte opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) { throw new FormatException("Format32bppArgb bitmap required"); } IntPtr screenDc = NativeMethods.GetDC(IntPtr.Zero); IntPtr memDc = NativeMethods.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); oldBitmap = NativeMethods.SelectObject(memDc, hBitmap); NativeStructs.SIZE size = new NativeStructs.SIZE(bitmap.Width, bitmap.Height); NativeStructs.POINT pointSource = new NativeStructs.POINT(0, 0); NativeStructs.POINT topPos = new NativeStructs.POINT(Left, Top); NativeStructs.BLENDFUNCTION blend = new NativeStructs.BLENDFUNCTION(); blend.BlendOp = NativeConsts.AC_SRC_OVER; blend.BlendFlags = 0; blend.SourceConstantAlpha = opacity; blend.AlphaFormat = NativeConsts.AC_SRC_ALPHA; NativeMethods.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, NativeConsts.ULW_ALPHA); } finally { NativeMethods.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { NativeMethods.SelectObject(memDc, oldBitmap); NativeMethods.DeleteObject(hBitmap); } NativeMethods.DeleteDC(memDc); } }