public void DrawBitmap(Bitmap bmp, byte opacity) { IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; IntPtr screenDc = NativeMethods.GetDC(IntPtr.Zero); IntPtr memDc = NativeMethods.CreateCompatibleDC(screenDc); try { hBitmap = bmp.GetHbitmap(Color.FromArgb(0)); oldBitmap = NativeMethods.SelectObject(memDc, hBitmap); SIZE size = new SIZE(bmp.Width, bmp.Height); POINT pointSource = new POINT(this.Left, this.Top); POINT topPos = new POINT(0, 0); BLENDFUNCTION blend; blend.BlendOp = 0; blend.BlendFlags = 0; blend.SourceConstantAlpha = byte.MaxValue; blend.AlphaFormat = 1; NativeMethods.UpdateLayeredWindow(this.Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, 2); } catch (Exception ex) { throw ex; } finally { NativeMethods.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { NativeMethods.SelectObject(memDc, oldBitmap); NativeMethods.DeleteObject(hBitmap); } NativeMethods.DeleteDC(memDc); } }
public void SelectBitmap(Bitmap bitmap, int opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) { throw new ApplicationException("The bitmap must be 32bpp with alpha-channel."); } IntPtr screenDc = NativeMethods.GetDC(IntPtr.Zero); IntPtr memDc = NativeMethods.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr hOldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); hOldBitmap = NativeMethods.SelectObject(memDc, hBitmap); SIZE newSize = new SIZE(bitmap.Width, bitmap.Height); POINT sourceLocation = new POINT(0, 0); POINT newLocation = new POINT(this.Left, this.Top); BLENDFUNCTION blend = new BLENDFUNCTION(); blend.BlendOp = NativeMethods.AC_SRC_OVER; blend.BlendFlags = 0; blend.SourceConstantAlpha = (byte)opacity; blend.AlphaFormat = NativeMethods.AC_SRC_ALPHA; NativeMethods.UpdateLayeredWindow(this.Handle, screenDc, ref newLocation, ref newSize, memDc, ref sourceLocation, 0, ref blend, NativeMethods.ULW_ALPHA); } finally { NativeMethods.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { NativeMethods.SelectObject(memDc, hOldBitmap); NativeMethods.DeleteObject(hBitmap); } NativeMethods.DeleteDC(memDc); } }
public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize, IntPtr hdcSrc, ref POINT pptSrc, uint crKey, [In] ref BLENDFUNCTION pblend, uint dwFlags);
public static extern int DwmQueryThumbnailSourceSize(IntPtr thumb, out SIZE size);