Page Top

WPF 窗体使用 Show() 单个显示并设置弹窗相对于主窗体位置

代码示例:

WndNavigation _wnd = null;   // WPF窗体全局变量

/// <summary>
/// 适用Show仅打开一个窗体,并显示在相对于主窗体的位置
/// </summary>
private void OpenWnd()
{
    if (_wnd == null || !_wnd.IsLoaded)
    {
        _wnd = new WndNavigation();
        _wnd.Closing += (s, e) => { _wnd = null; };
        _wnd.WindowStartupLocation = WindowStartupLocation.Manual;
        Window owner = System.Windows.Application.Current.MainWindow;
        _wnd.Owner = owner;
        if (owner != null)
        {
            #region 设置本窗体位置
            System.Windows.Point pLeft = owner.PointToScreen(new System.Windows.Point(0, 0));
            IntPtr hwnd = new WindowInteropHelper(owner).Handle;
            HwndSource hwndSource = HwndSource.FromHwnd(hwnd);
            if (hwndSource != null)
                pLeft = hwndSource.CompositionTarget.TransformFromDevice.Transform(pLeft);

            // 在主窗体右上角
            //Point rightTop = new Point(pLeft.X + owner.ActualWidth, pLeft.Y);
            //_wnd.Left = rightTop.X - _wnd.Width - 80;
            //_wnd.Top = rightTop.Y + 25;

            System.Windows.Point rightBottom = new System.Windows.Point(pLeft.X + owner.ActualWidth, pLeft.Y + owner.ActualHeight);

            // 在主窗体右下角
            _wnd.Left = rightBottom.X - _wnd.Width - 110;
            _wnd.Top = rightBottom.Y - _wnd.Height - 70;
            #endregion
        }
        else
        {
            _wnd.Left = SystemParameters.WorkArea.Width - 280;
            _wnd.Top = SystemParameters.WorkArea.Height - 100;
        }
    }

    _wnd.Topmost = true;

    if (!_wnd.IsLoaded)
        _wnd.Show();
    else
        _wnd.Activate();
}

End~

 

posted @ 2021-12-13 14:06  抹茶大虾球丶  阅读(989)  评论(0编辑  收藏  举报