I'm trying to capture desktop windows in C# based on Window handles. I'm using .NET and using PInvoke to GetWindowRect() to capture the window rectangle. I've got the Window selection and rectangle capture working fine.
However, the window rectangles captured include not just the actual window size but also the Window's adornments like the shadow around it. When I try to clip the window to a bitmap the bitmap contains the area and shadow. On Windows 10 I get the transparent shadow area including any content that might be visible below the active window:
The code I use is simple enough capturing the Window using Win32 GetWindowRect() via PInvoke call:
var rect = new Rect();
GetWindowRect(handle, ref rect);
var bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
var result = new Bitmap(bounds.Width, bounds.Height);
using (var graphics = Graphics.FromImage(result))
{
graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
return result;
I then capture the image and assign it into a picture box.
In addition it looks like there's some variation between windows - some windows have shadows others do not. Most do, but some like Visual Studio and Chrome do not, so it's not even a simple matter of stripping out the extraneous pixels.
I've tried using GetClientRect() but that gets me just the client area which is not what I've after. What I'd like to get is the actual Window rectangle with borders but without the shadows.
Is there anyway to do this?
GetWindowDC
) - this will get the window even if it's covered by another one. Also, see the 3rd comment on this page. – MochaCS_DROPSHADOW
flag, capture the window, and revert the mask. – VondavonniDwmGetWindowAttribute
DwmGetWindowAttribute function withDWMWA_EXTENDED_FRAME_BOUNDS
attribute. – LundDwmGetWindowAttribute
is the solution. It should give a rectangle which is smaller than the rectangle from GetWindowRect. – Noisome