在C#中使用BitBlt捕获的屏幕截图在Windows 10上显示黑色图像 [英] Screenshot captured using BitBlt in C# results a black image on Windows 10

查看:882
本文介绍了在C#中使用BitBlt捕获的屏幕截图在Windows 10上显示黑色图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c#中使用 BitBlt 捕获的屏幕截图在 Windows 10 上显示黑色图像.请帮我解决这个问题.

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

屏幕截图是Chrome(启用硬件加速模式时)和IE/Edge窗口的黑色图像.

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

当硬件加速模式为ON时,仅Edge,Windows 10中的IE浏览器窗口和Chrome浏览器窗口的输出图像为黑色.除了透明窗口截图以外的所有其他窗口都是不错的选择.

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.

这是代码:

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);

推荐答案

硬件加速窗口是使用叠加模式渲染的,这意味着您的BitBlt仅获得表示嘿,这是叠加!"的像素.当不渲染叠加层时,将生成黑色图像-如果正在渲染,则始终会看到 current 渲染,而不是时间冻结的东西.您不会捕获屏幕上显示的像素,而只是捕获窗口渲染方式的一些内部细节.

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);

(您可以将BitBlt P/Invoke定义修改为使用CopyPixelOperation而不是int,或仅将这些值强制转换为int).

(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.

这篇关于在C#中使用BitBlt捕获的屏幕截图在Windows 10上显示黑色图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆