如何通过z-index对Windows进行排序?

Fyo*_*kin 6 wpf z-index

如果我在枚举窗口Application.Current.Windows,我怎么能知道,对于任何两个窗口,哪一个"更接近"(即具有更大的z-index)?

或者,换句话说,我怎样才能通过z-index对这些窗口进行排序?

Ray*_*rns 7

您无法从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);
Run Code Online (Sandbox Code Playgroud)

这种方式的工作原理是:

  1. 它使用字典按窗口句柄索引给定的窗口,使用的事实是,在WPF的Windows实现中,Window的PresentationSource始终是HwndSource.
  2. 它使用Win32从上到下扫描所有未显示的窗口,以找到正确的顺序.