Get window size without windows shadows

I am trying to capture desktop windows in C # based on window handles. I use .NET and use PInvoke for GetWindowRect () to capture the rectangle of the window. I have a window selection and a rectangle capture that works fine.

However, the captured rectangles of the window include not only the actual size of the window, but also windows, such as the shadow around it. When I try to copy a window into a bitmap, the bitmap contains an area and a shadow. On Windows 10, I get a transparent shadow area, including any content that can be seen under the active window:

enter image description here

The code I use is quite simple, capturing a Window using Win32 GetWindowRect () via a 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; 

Then I capture the image and assign it to the image window.

In addition, it seems that there are some differences between the windows - some windows have shadows that are not there. Most of them, but some, such as Visual Studio and Chrome, do not do this, so it’s not even easy to remove extra pixels.

I tried using GetClientRect (), but this only gives me the client area, which is not what I got after. What I would like to get is the actual Window rectangle with borders but no shadows.

Is there any way to do this?

+8
c # windows winapi pinvoke
source share
1 answer

I run Windows 10 and faced the same problem when writing an application to snap windows to the top or bottom of the screen. I found DwmGetWindowAttribute () to work. It returns a RECT with slightly different values ​​than GetWindowRect () ...

Results from the sample window:

GetWindowRect (): {X = 88, Y = 26, Width = 871, Height = 363}

DwmGetWindowAttribute (): {X = 95, Y = 26, Width = 857, Height = 356}

My testing showed that GetWindowRect () includes decorations, while DwmGetWindowAttribute () does not.

If you get the same results for both methods in the window with decorations, it is possible that this particular window draws its own decorations or that there is some other attribute or property in the window that needs to be taken into account.

+1
source share

All Articles