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~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM