public static Win32Bitmap Create(IntPtr hdc, int width, int height) { IntPtr bitmapPtr = IntPtr.Zero; IntPtr bitmapHdc = IntPtr.Zero; try { bitmapPtr = Gdi32API.CreateCompatibleBitmapChecked(hdc, width, height); bitmapHdc = Gdi32API.CreateCompatibleDCChecked(hdc); Gdi32API.SelectObjectChecked(bitmapHdc, bitmapPtr); var bitmap = new Win32Bitmap(bitmapPtr, bitmapHdc, width, height); bitmapPtr = IntPtr.Zero; bitmapHdc = IntPtr.Zero; return(bitmap); } finally { if (bitmapHdc != IntPtr.Zero) { Gdi32API.DeleteDC(bitmapHdc); } if (bitmapPtr != IntPtr.Zero) { Gdi32API.DeleteObject(bitmapPtr); } } }
private void WithTransparentCanvas(Rectangle rect, byte alpha, bool copySource, Action <Win32Canvas> action) { if (rect.Width <= 0 || rect.Height <= 0 || alpha == 0) { return; } IntPtr memoryHdc = Gdi32API.CreateCompatibleDCChecked(hdc); try { IntPtr memoryBitmap = Gdi32API.CreateCompatibleBitmapChecked(hdc, rect.Width, rect.Height); try { var originalBitmap = Gdi32API.SelectObjectChecked(memoryHdc, memoryBitmap); try { if (copySource) { Gdi32API.BitBlt(memoryHdc, 0, 0, rect.Width, rect.Height, hdc, rect.X, rect.Y, GDI32RasterOperation.SRCCOPY); } using (Win32Canvas memoryCanvas = new Win32Canvas(memoryHdc, offset, objectCache)) { action(memoryCanvas); } Gdi32API.GdiAlphaBlend ( hdc, rect.X, rect.Y, rect.Width, rect.Height, memoryHdc, 0, 0, rect.Width, rect.Height, BLENDFUNCTION.ConstantAlpha(alpha) ); } finally { Gdi32API.SelectObjectChecked(memoryHdc, originalBitmap); } } finally { Gdi32API.DeleteObject(memoryBitmap); } } finally { Gdi32API.DeleteDC(memoryHdc); } }