问题描述
我使用BitBlt()和CreateBitmapSourceFromHBitmap()将窗口捕获为BitmapSource,可以在WPF应用程序的Image元素上显示该窗口.但是由于某种原因,它捕获的大多数应用程序都是透明的.这是正在发生的事件的源图像和捕获图像:
I use BitBlt() and CreateBitmapSourceFromHBitmap() to capture a window as a BitmapSource that I can display on an Image element in a WPF application. But for some reason, most of the application that it captures is transparent. Here is a source vs. capture image of what's happening:
它是灰色的,因为它所在的窗口的背景是灰色的.无论我给窗口提供什么背景,都将显示出来.
It's gray because the background of the window it's on is gray. Whatever background I give the window will show through.
如何获取拍摄的图像以更准确地反映原始图像?
How can I get the captured image to more accurately reflect the original?
推荐答案
代码中的问题可能是由于您使用的Win32 API(CreateCompatibleDC
,SelectObject
,CreateBitmap
...)引起的.我尝试了一个简单的代码,仅使用GetDC
和BitBlt
,它对我来说很好用.这是我的代码:
The problem in your code could be due to the Win32 API you're using (CreateCompatibleDC
, SelectObject
, CreateBitmap
...). I tried with a simpler code, using only GetDC
and BitBlt
, and it works fine for me. Here's my code:
public static Bitmap Capture(IntPtr hwnd)
{
IntPtr hDC = GetDC(hwnd);
if (hDC != IntPtr.Zero)
{
Rectangle rect = GetWindowRectangle(hwnd);
Bitmap bmp = new Bitmap(rect.Width, rect.Height);
using (Graphics destGraphics = Graphics.FromImage(bmp))
{
BitBlt(
destGraphics.GetHdc(),
0,
0,
rect.Width,
rect.Height,
hDC,
0,
0,
TernaryRasterOperations.SRCCOPY);
}
return bmp;
}
return null;
}
我在Windows Forms和WPF(使用Imaging.CreateBitmapSourceFromHBitmap
)中进行了尝试,在两种情况下,对于相同的屏幕截图(Firefox中的SO页面),它都可以正常工作.
I tried it in Windows Forms and WPF (with Imaging.CreateBitmapSourceFromHBitmap
), it works fine in both cases for the same screenshot (SO page in Firefox).
HTH,
这篇关于从BitmapSource删除Alpha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!