hello world

WPF获取顶部的窗口

       
     //从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);
        }    

 

posted @ 2021-03-15 09:27  我是刹那、  阅读(602)  评论(0编辑  收藏  举报