/// <summary> /// 设置图象 /// </summary> protected void SetBitmap(Bitmap bitmap, byte opacity = 255) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) { throw new ApplicationException("The bitmap must be 32bpp with alpha-channel."); } this.ClientSize = new Size(bitmap.Width, bitmap.Height); // The idea 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 = GetDC(IntPtr.Zero); IntPtr memDc = CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); // Grab a GDI handle from this GDI+ bitmap oldBitmap = SelectObject(memDc, hBitmap); ExtSize size = new ExtSize(bitmap.Width, bitmap.Height); ExtPoint pointSource = new ExtPoint(0, 0); ExtPoint topPos = new ExtPoint(this.Left, this.Top); ExtBlendFunction blend = new ExtBlendFunction { BlendOp = AC_SRC_OVER, BlendFlags = 0, SourceConstantAlpha = opacity, AlphaFormat = AC_SRC_ALPHA }; UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, ULW_ALPHA); } finally { ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { SelectObject(memDc, oldBitmap); // The documentation says that we have to use the Windows.DeleteObject... // but since there is no such method I use the normal DeleteObject from Win32 GDI // and it's working fine without any resource leak. // // Windows.DeleteObject(hBitmap); DeleteObject(hBitmap); } DeleteDC(memDc); } bitmap.Dispose(); }
private static extern Bool UpdateLayeredWindow(IntPtr hWnd, IntPtr hdcDst, ref ExtPoint pptDst, ref ExtSize psize, IntPtr hDcSrc, ref ExtPoint pprSrc, int crKey, ref ExtBlendFunction pblend, int dwFlags);