//从Handle中获取Window对象 private static Window GetWindowFromHwnd(IntPtr hwnd) { var fromHwnd = HwndSource.FromHwnd(hwnd); if (fromHwnd != null) return (Window)fromHwnd.RootVisual; return null; } [DllImport("user32.dll")] static extern IntPtr GetActiveWindow(); /////调用GetForegroundWindow然后调用GetWindowFromHwnd /// <summary> /// 获取当前*窗体,若获取失败则返回主窗体 /// </summary> public static Window GetTopWindow() { var hwnd = GetActiveWindow(); if (hwnd == IntPtr.Zero) return Application.Current.MainWindow; return GetWindowFromHwnd(hwnd); }