I want to move and resize an application's window (ex: Notepad).
I tried both MoveWindow
and SetWindowPos
, and both has the exact same issue. The new position/size is always inaccurate.
MoveWindow(handle, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, true);
SetWindowPos(handle, IntPtr.Zero, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height, 0);
I tested this on different PCs (both running Windows 10) and I noticed a pattern. On the first PC, the "drift" was X:+7, Y:0, W: -14, H: -7. On the second PC, the "drift" was X:+8, Y:0, W:-16, H-8.
I did test it on a third PC, but the result was way worse which I'm guessing it has something to do with it having 2 monitors.
I can see the "drift" with my own eyes, it's especially clear when I feed it X:0 and Y:0. I don't understand why this is happening though or how I can fix it.
This is the function I use to get a Window's (ex: Notepad) position and dimensions:
public static Rectangle GetWindowRectangle(IntPtr handle)
{
Rect rect = new Rect();
if (Environment.OSVersion.Version.Major >= 6)
{
int size = Marshal.SizeOf(typeof(Rect));
DwmGetWindowAttribute(handle, (int)DwmWindowAttribute.DWMWA_EXTENDED_FRAME_BOUNDS, out rect, size);
}
else if (Environment.OSVersion.Version.Major < 6 || rect.ToRectangle().Width == 0)
{
GetWindowRect(handle, out rect);
}
return rect.ToRectangle();
}
question from:
https://stackoverflow.com/questions/65599491/both-movewindow-and-setwindowpos-result-in-incorrect-window-position-size 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…