我有一些代码将窗口定位到屏幕象限。它适用于Windows XP,7和8 / 8.1。但是,在Windows 10上,窗口之间存在奇怪的差距。四面环绕窗户的额外空间。我认为它与窗口边界有关,但无法弄清楚如何纠正问题。任何意见都将受到高度赞赏。代码如下:
// Get monitor info
HMONITOR hm = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);
MONITORINFO mi;
mi.cbSize = sizeof(mi);
GetMonitorInfo(hm, &mi);
// Set screen coordinates and dimensions of monitor's work area
DWORD x = mi.rcWork.left;
DWORD y = mi.rcWork.top;
DWORD w = mi.rcWork.right - x;
DWORD h = mi.rcWork.bottom - y;
switch (corner) {
case 0: // Left top
SetWindowPos(hWnd, HWND_TOP, x, y, w / 2, h / 2, SWP_NOZORDER);
break;
case 1: // Right top
SetWindowPos(hWnd, HWND_TOP, x + w / 2, y, w / 2, h / 2, SWP_NOZORDER);
break;
case 2: // Right bottom
SetWindowPos(hWnd, HWND_TOP, x + w / 2, y + h / 2, w / 2, h / 2, SWP_NOZORDER);
break;
case 3: // Left bottom
SetWindowPos(hWnd, HWND_TOP, x, y + h / 2, w / 2, h / 2, SWP_NOZORDER);
break;
}
我设法通过计算边距膨胀目标矩形来纠正这种效果,如下所示:
static RECT GetSystemMargin(IntPtr handle) {
HResult success = DwmGetWindowAttribute(handle, DwmApi.DWMWINDOWATTRIBUTE.DWMWA_EXTENDED_FRAME_BOUNDS,
out var withMargin, Marshal.SizeOf<RECT>());
if (!success.Succeeded) {
Debug.WriteLine($"DwmGetWindowAttribute: {success.GetException()}");
return new RECT();
}
if (!GetWindowRect(handle, out var noMargin)) {
Debug.WriteLine($"GetWindowRect: {new Win32Exception()}");
return new RECT();
}
return new RECT {
left = withMargin.left - noMargin.left,
top = withMargin.top - noMargin.top,
right = noMargin.right - withMargin.right,
bottom = noMargin.bottom - withMargin.bottom,
};
}
然后做
RECT systemMargin = GetSystemMargin(this.Handle);
targetBounds.X -= systemMargin.left;
targetBounds.Y -= systemMargin.top;
targetBounds.Width += systemMargin.left + systemMargin.right;
targetBounds.Height += systemMargin.top + systemMargin.bottom;
这适用于我可以测试它的所有窗口,除了资源管理器窗口,我硬编码排除。如果我在屏幕边缘附近的资源管理器上进行扩展,窗口最终会溢出大面积区域到达相邻的显示器。
Windows XP / 7/8 / 8.1的默认字体大小为100%,但在Windows 10中,默认情况下以125%显示文本和项目。这会直接影响所有窗口大小。
转到设置,显示,你会找到一个滚动条,将其移动到100%,一切都应该像在Windows 8/7 / XP中一样显示