/// <summary> /// Capture transparent Screenshot of a Window. /// </summary> /// <param name="Window">The <see cref="Window"/> to Capture.</param> /// <param name="IncludeCursor">Whether to include Mouse Cursor.</param> public static Bitmap CaptureTransparent(Window Window, bool IncludeCursor = false) { if (Window == null) { throw new ArgumentNullException(nameof(Window)); } var backdrop = new Form { AllowTransparency = true, BackColor = Color.White, FormBorderStyle = FormBorderStyle.None, ShowInTaskbar = false, Opacity = 0 }; var r = new RECT(); const int extendedFrameBounds = 0; if (DwmGetWindowAttribute(Window.Handle, extendedFrameBounds, ref r, Marshal.SizeOf <RECT>()) != 0) { // DwmGetWindowAttribute() failed, usually means Aero is disabled so we fall back to GetWindowRect() User32.GetWindowRect(Window.Handle, out r); } var R = r.ToRectangle(); // Add a 100px margin for window shadows. Excess transparency is trimmed out later R.Inflate(100, 100); // This check handles if the window is outside of the visible screen R.Intersect(WindowProvider.DesktopRectangle); ShowWindow(backdrop.Handle, 4); SetWindowPos(backdrop.Handle, Window.Handle, R.Left, R.Top, R.Width, R.Height, SetWindowPositionFlags.NoActivate); backdrop.Opacity = 1; Application.DoEvents(); // Capture screenshot with white background using (var whiteShot = Capture(R)) { backdrop.BackColor = Color.Black; Application.DoEvents(); // Capture screenshot with black background using (var blackShot = Capture(R)) { backdrop.Dispose(); var transparentImage = Extensions.DifferentiateAlpha(whiteShot, blackShot); if (transparentImage == null) { return(null); } if (IncludeCursor) { using (var g = Graphics.FromImage(transparentImage)) MouseCursor.Draw(g, P => new Point(P.X - R.X, P.Y - R.Y)); } return(transparentImage.CropEmptyEdges()); } } }