这是我的另一个问题的延续(不需要理解它,仅供参考):
事实证明我正在使用的Graphics.CopyFromScreen具有以下人工制品 - 它假设我想要使用透明度密钥= Color.Black进行复制,因此它会跳过那些非常暗的区域 - 我的桌面背景图像的一部分 - 他们突然出现在白色,现在看起来很难看:
我目前使用的代码如下:
private static Bitmap MakeScreenshot()
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
Bitmap image = new Bitmap(bounds.Width, bounds.Height);
using (Graphics g = Graphics.FromImage(image))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
return image;
}
An answer by Hans Passant建议使用 p / invoke ,但是对于另一个问题 - 分层窗口 - 所以我尝试了,并且工作,下面是等效代码,但现在使用WinApi:
public static Bitmap CreateBitmapFromDesktopNew()
{
Size sz = GetDesktopBounds().Size;
IntPtr hDesk = GetDesktopWindow();
IntPtr hSrce = GetWindowDC(hDesk);
IntPtr hDest = CreateCompatibleDC(hSrce);
IntPtr hBmp = CreateCompatibleBitmap(hSrce, sz.Width, sz.Height);
IntPtr hOldBmp = SelectObject(hDest, hBmp);
bool b = BitBlt(hDest, 0, 0, sz.Width, sz.Height, hSrce, 0, 0, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt);
Bitmap bmp = Bitmap.FromHbitmap(hBmp);
SelectObject(hDest, hOldBmp);
DeleteObject(hBmp);
DeleteDC(hDest);
ReleaseDC(hDesk, hSrce);
return bmp;
}
问题:是否有解决我特定问题的原生.NET方法?如果有更好的方法,我试图避免使用WinApi。