Screenshot captured using BitBlt in C# results a black image on Windows 10

情到浓时终转凉″ 提交于 2019-12-18 17:28:28

问题


Screenshot captured using BitBlt in c# resulted a black image on Windows 10. Please help me to resolve this.

Screenshot is black image for Chrome (when hardware accelerated mode is on) and IE/Edge windows.

Output image is black only for Edge, IE browser windows in Windows 10 and Chrome browser window when hardware accelerated mode is ON. Apart from all other windows including transparent windows screenshots are good.

Here is the code:

const int Srccopy = 0x00CC0020;
var windowRect = new Rect();

GetWindowRect(handle, ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;

// get te hDC of the target window
IntPtr hdcSrc = GetWindowDC(handle);

// create a device context we can copy to
IntPtr hdcDest = CreateCompatibleDC(hdcSrc);

// create a bitmap we can copy it to,
IntPtr hBitmap = CreateCompatibleBitmap(hdcSrc, width, height);
// select the bitmap object
IntPtr hOld = SelectObject(hdcDest, hBitmap);

// bitblt over
BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, Srccopy);
// restore selection
SelectObject(hdcDest, hOld);
// clean up
DeleteDC(hdcDest);
ReleaseDC(handle, hdcSrc);

Image img = Image.FromHbitmap(hBitmap);
// free up the Bitmap object
DeleteObject(hBitmap);

回答1:


Hardware accelerated windows are rendered using overlay mode, which means that your BitBlt only gets pixels that say "Hey, this is overlay!". When the overlay isn't being rendered, this results in a black image - and if it is being rendered, you always see the current render, not something frozen in time. You're not capturing the pixels being shown on the screen, just some internal details of how window rendering works.

The solution is fortunately quite simple:

BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, 
       CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt);

(you can modify your BitBlt P/Invoke definition to use CopyPixelOperation instead of int, or just cast those values to int yourself).

As a side-note, please don't forget to check the return values and handle errors accordingly.



来源:https://stackoverflow.com/questions/38868275/screenshot-captured-using-bitblt-in-c-sharp-results-a-black-image-on-windows-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!