1

I have searched all the topics in stackoverflow and tried all the suggestions, but Printwindow keeps giving me black, partial or practically blank screens. I refer to inactive / minimized applications especially. I was reading that it could be due to some apps that handle this functionality badly, but this also happens with explorer.exe, and I want to hope that the problem is not attributable to this.

My goal is to create a window selector similar to what appears in Zoom when you do screen sharing.

Is there any alternative method?

For completeness I report the function I used, even if it is the same as reported on some question in stackoverflow.

(two proven methods)

public static Bitmap GetScreenshot(IntPtr hwnd)
    {
        
        RECT rc;
        GetWindowRect(new HandleRef(null, hwnd), out rc);

        Bitmap bmp = new Bitmap(rc.Right - rc.Left, rc.Bottom - rc.Top, PixelFormat.Format32bppArgb);
        Graphics gfxBmp = Graphics.FromImage(bmp);
        IntPtr hdcBitmap;
        try
        {
            hdcBitmap = gfxBmp.GetHdc();
        }
        catch
        {
            return null;
        }
        bool succeeded = PrintWindow(hwnd, hdcBitmap, 0);
        gfxBmp.ReleaseHdc(hdcBitmap);
        if (!succeeded)
        {
            gfxBmp.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(Point.Empty, bmp.Size));
        }
        IntPtr hRgn = CreateRectRgn(0, 0, 0, 0);
        GetWindowRgn(hwnd, hRgn);
        Region region = Region.FromHrgn(hRgn);//err here once
        if (!region.IsEmpty(gfxBmp))
        {
            gfxBmp.ExcludeClip(region);
            gfxBmp.Clear(Color.Transparent);
        }
        gfxBmp.Dispose();
        return bmp;
    }

public static Bitmap PrintWindow(IntPtr hwnd)
    {
        RECT rc;
        GetWindowRect(hwnd, out rc);

        Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);
        Graphics gfxBmp = Graphics.FromImage(bmp);
        IntPtr hdcBitmap = gfxBmp.GetHdc();

        PrintWindow(hwnd, hdcBitmap, 0);

        gfxBmp.ReleaseHdc(hdcBitmap);
        gfxBmp.Dispose();

        return bmp;
    }
Daniele
  • 11
  • 2
  • Does this answer your question? [How to get a thumbnail of a window in C#?](https://stackoverflow.com/questions/1464298/how-to-get-a-thumbnail-of-a-window-in-c) – Raymond Chen Oct 17 '21 at 19:01
  • 2
    I found a solution to the black image problem. Try putting in the value of 2 as the 3rd parameter (flags) for `PrintWindow`. After some digging I found the following in the chromium source: _"The PW_RENDERFULLCONTENT flag is undocumented, but works starting in Windows 8.1. It allows for capturing the contents of the window that are drawn using DirectComposition."_ `UINT flags = PW_CLIENTONLY | PW_RENDERFULLCONTENT;` and so I do: `int PW_CLIENTONLY = 0x1; int PW_RENDERFULLCONTENT = 0x2; PrintWindow(hwnd, hdcBitmap, PW_CLIENTONLY | PW_RENDERFULLCONTENT);` – Jargon Jul 20 '22 at 15:37

0 Answers0