如果我枚举窗口Application.Current.Windows
,对于任意两个窗口,我如何判断哪一个“更接近”(即具有更大的 z-index)?
或者,换句话说,我如何按 z 索引对这些窗口进行排序?
您无法从 WPF 获取 Window 的 Z Order 信息,因此必须求助于 Win32。
像这样的事情应该可以解决问题:
var topToBottom = SortWindowsTopToBottom(Application.Current.Windows.OfType<Window>());
...
public IEnumerable<Window> SortWindowsTopToBottom(IEnumerable<Window> unsorted)
{
var byHandle = unsorted.ToDictionary(win =>
((HwndSource)PresentationSource.FromVisual(win)).Handle);
for(IntPtr hWnd = GetTopWindow(IntPtr.Zero); hWnd!=IntPtr.Zero; hWnd = GetWindow(hWnd, GW_HWNDNEXT)
if(byHandle.ContainsKey(hWnd))
yield return byHandle[hWnd];
}
const uint GW_HWNDNEXT = 2;
[DllImport("User32")] static extern IntPtr GetTopWindow(IntPtr hWnd);
[DllImport("User32")] static extern IntPtr GetWindow(IntPtr hWnd, uint wCmd);
它的工作方式是:
- 它使用字典通过窗口句柄对给定窗口进行索引,利用以下事实:在 WPF 的 Windows 实现中,窗口的PresentationSource 始终是 HwndSource。
- 它使用 Win32 从上到下扫描所有无父窗口,以找到正确的顺序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)