好的,所以我的previous question没有产生任何有用的答案,所以我将尝试从不同的方向。
我的应用程序可能有几个窗口。给定屏幕坐标中的一个点,我需要找出它“落在”哪个窗口上--即找到包含该点的所有窗口中最前面的窗口。
如果它们是一个窗口中的Visual,我会使用VisualTreeHelper.HitTest。但是因为它们是不同的窗口,所以不清楚该给该方法提供什么作为第一个参数。
发布于 2010-08-13 12:43:48
使用纯WPF是不可能的,因为WPF不公开其窗口的Z顺序。事实上,WPF努力保持这样一种假象,即窗口实际上永远不会相互遮挡。
如果您愿意调用Win32,那么解决方案很简单:
public Window FindWindowAt(Point screenPoint) // WPF units (96dpi), not device units
{
return (
from win in SortWindowsTopToBottom(Application.Current.Windows.OfType<Window>())
where new Rect(win.Left, win.Top, win.Width, win.Height).Contains(screenPoint)
select win
).FirstOrDefault();
}
public static 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); 如果您的窗口可能是透明的,那么还应该在FindWindowAt()的"where“子句中使用VisualTreeHelper.HitTest。
https://stackoverflow.com/questions/3473312
复制相似问题