This is a continuation of my other question (understanding of it is not required, just for reference):
It turns out that Graphics.CopyFromScreen which I'm using has the following artefact - it assumes I want to copy with transparency key = Color.Black, so it skips those very dark areas - part of my desktop background image - they suddenly appear in white, and now it looks rather ugly:
The code I'm currently using is provided below:
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 suggested using a p/invoke instead, but for a different issue - layered windows - so I tried that, and it worked, below is equivalent code, but now using 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;
}
Question: Is there a native .NET approach that solves my particular problem? I'm trying to avoid using WinApi if there is a better way of doing it.