gpt4 book ai didi

wpf - 如何按 z-index 对 Windows 进行排序?

转载 作者:行者123 更新时间:2023-12-04 14:40:46 24 4
gpt4 key购买 nike

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

或者,换句话说,我如何按 z-index 对这些窗口进行排序?

最佳答案

您无法从 WPF 获取窗口的 Z 顺序信息,因此您必须求助于 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 实现中,Window 的 PresentationSource 始终是 HwndSource。
  • 它使用 Win32 从上到下扫描所有无父级窗口以找到正确的顺序。
  • 关于wpf - 如何按 z-index 对 Windows 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3473016/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com