Capture screenshot Including Semitransparent windows in .NET

Forms that have the TransparencyKey or Opacity property set are so-called layered windows. They are shown using the “overlay” feature of the video adapter. Which make them being able to have their transparency effects.

Capturing them requires turning on the CopyPixelOperation.CaptureBlt option in the CopyFromScreen overload that accepts the CopyPixelOperation argument.

Unfortunately, this overload has a critical bug that prevents this from working. It doesn’t validate the value properly. Still not fixed in .NET 4.0. There is no other good fix but fall back to using P/Invoke to make the screen shot. Here’s an example:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1 {
  public partial class Form1 : Form {
    public Form1() {
    private void button1_Click(object sender, EventArgs e) {
      Size sz = Screen.PrimaryScreen.Bounds.Size;
      IntPtr hDesk = GetDesktopWindow();
      IntPtr hSrce = GetWindowDC(hDesk);
      IntPtr hDest = CreateCompatibleDC(hSrce);
      IntPtr hBmp = CreateCompatibleBitmap(hSrce, sz.Width, sz.Height);
      IntPtr hOldBmp = SelectObject(hDest, hBmp);
      bool b = BitBlt(hDest, 0, 0, sz.Width, sz.Height, hSrce, 0, 0, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt);
      Bitmap bmp = Bitmap.FromHbitmap(hBmp);
      SelectObject(hDest, hOldBmp);
      ReleaseDC(hDesk, hSrce);

    // P/Invoke declarations
    static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int
    wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, CopyPixelOperation rop);
    static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDc);
    static extern IntPtr DeleteDC(IntPtr hDc);
    static extern IntPtr DeleteObject(IntPtr hDc);
    static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
    static extern IntPtr CreateCompatibleDC(IntPtr hdc);
    static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp);
    public static extern IntPtr GetDesktopWindow();
    public static extern IntPtr GetWindowDC(IntPtr ptr);

Fwiw, a later Windows version provided a workaround for this bug. Not exactly sure which, I think it was Win7 SP1. The BitBlt() function will now do what you want if you pass only the CopyPixelOperation.CaptureBlt option. But of course that workaround wasn’t applied retro-actively to earlier Windows versions so you can’t really depend on it.

Leave a Comment