我使用 BitBlt() 和 CreateBitmapSourceFromHBitmap() 来捕获窗口作为 BitmapSource,我可以将其显示在 WPF 应用程序中的 Image 元素上。但由于某种原因,它捕获的大部分应用程序都是透明的。这是正在发生的事情的源与捕获图像:
(来源:umbc.edu)
它是灰色的,因为它所在的窗口背景是灰色的。无论我给窗口设置什么背景都会显示出来。
如何让捕获的图像更准确地反射(reflect)原始图像?
最佳答案
代码中的问题可能是由于您使用的 Win32 API 造成的(CreateCompatibleDC
、SelectObject
、CreateBitmap
...) 。我尝试使用更简单的代码,仅使用 GetDC
和 BitBlt
,它对我来说效果很好。这是我的代码:
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 窗体和 WPF 中尝试了它(使用 Imaging.CreateBitmapSourceFromHBitmap
),对于相同的屏幕截图(Firefox 中的 SO 页面),在这两种情况下都可以正常工作。
HTH,
关于c# - 从 BitmapSource 中删除 Alpha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1738059/