[英]Compute total width of title bar buttons for 3rd party window on windows 10
我最初的方法是使用GetSystemMetrics
和SystemMetric.SM_CXSIZE
以及一些基于按钮可用(3 次或 1 次)的简单数学,通过WindowStyle
。
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(SystemMetric smIndex);
这在 Windows 10 上存在问题,其中计算出的宽度约为实际宽度的 70%。 所以宽度只覆盖两个按钮 - 最大化和关闭。 Windows 7 和 8.1 很好,相同的 DPI 设置,它涵盖了所有按钮。
我检查了 Stack Overflow 上的一些现有问题,并且从 2011 年开始在这个问题上取得了最大的成功:
不幸的是,虽然建议的方法在 Windows 8.1 中有效,但它在 Windows 10(最新版本,所有推荐更新)上计算为 0。 有没有一种方法适用于从 7 到 10 的所有操作系统?
代码取自上述答案并修改为通过窗口句柄 (hwnd) 计算窗口控制按钮的总宽度,并将编组从 Rectangle 更改为 RECT (然后我得到正确的左/右值)。
public static int GetControlButtonsWidth(IntPtr hwnd)
{
// Create and initialize the structure
TITLEBARINFOEX tbi = new TITLEBARINFOEX();
tbi.cbSize = Marshal.SizeOf(typeof(TITLEBARINFOEX));
// Send the WM_GETTITLEBARINFOEX message
SendMessage(hwnd, WM_GETTITLEBARINFOEX, IntPtr.Zero, ref tbi);
int sum = tbi.rgrect.Sum(r => r.right - r.left);
// Return the filled-in structure
return sum;
}
internal const int WM_GETTITLEBARINFOEX = 0x033F;
internal const int CCHILDREN_TITLEBAR = 5;
[StructLayout(LayoutKind.Sequential)]
internal struct TITLEBARINFOEX
{
public int cbSize;
public RECT rcTitleBar;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = CCHILDREN_TITLEBAR + 1)]
public int[] rgstate;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = CCHILDREN_TITLEBAR + 1)]
public RECT[] rgrect;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(
IntPtr hWnd,
int uMsg,
IntPtr wParam,
ref TITLEBARINFOEX lParam);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left, top, right, bottom;
}
您可以使用DwmGetWindowAttribute
,这 3 个按钮的组合宽度在 Windows 10 上应为 185 像素,DPI 为 125%。 请注意,如果您的应用程序不支持 DPI,那么结果仍然相同,例如 185。
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("dwmapi.dll")]
public static extern int DwmGetWindowAttribute(
IntPtr hwnd, int attr, out RECT ptr, int size);
public void foo()
{
int DWMWA_CAPTION_BUTTON_BOUNDS = 5;
RECT rc;
if (0 != DwmGetWindowAttribute(this.Handle, DWMWA_CAPTION_BUTTON_BOUNDS,
out rc, Marshal.SizeOf(typeof(RECT))))
{
//error
}
int width = rc.right - rc.left;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.