文章出處

設置多屏時窗口居中顯示

問題:

在多個顯示屏運行的情況下,如果將主窗口從當前顯示屏移動到另一顯示屏。

設置子窗口單例模式,在當前顯示屏時彈出后,在主窗口移動到另一顯示屏后,再彈出子窗口時,你會發現子窗口跑到原來顯示屏去了

----這是WPF的鍋

因為已經設置了WindowStartupLocation="CenterOwner",也加了Owner的情況下,窗口每次彈出,理論上就該和主窗口保持在同一屏幕的。

 

解決:

通過窗口的Activated添加委托,每次窗口喚醒,都重新設置窗口的Location

    subWindow.Left = screen.Bounds.Left + (screen.Bounds.Width - subWindow.Width) / 2;
    subWindow.Top = screen.Bounds.Top + (screen.Bounds.Height - subWindow.Height) / 2;

獲取當前主窗口所在的屏幕。

var screen = Screen.FromHandle(new WindowInteropHelper(mainWindow).Handle);

 

詳細:

通過給Window添加一個附加屬性即可

helper:WindowScreenHelper.IsWindowShowInCurrentScreen="True" 

  

public class WindowScreenHelper
{
    public static readonly DependencyProperty IsWindowShowInCurrentScreenProperty = DependencyProperty.RegisterAttached(
        "IsWindowShowInCurrentScreen", typeof(bool), typeof(WindowScreenHelper), new PropertyMetadata(default(bool), ShowWindowInCurrentScreen));

    private static void ShowWindowInCurrentScreen(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var window = d as Window;
        if (window != null)
        {
            window.Activated += ShowInCurrentScreenWindow_Activated;
        }
    }

    private static void ShowInCurrentScreenWindow_Activated(object sender, EventArgs e)
    {
        var subWindow = sender as Window;
        if (subWindow == null) return;
        if (GetIsWindowShowInCurrentScreen(subWindow))
        {
            var mainWindow = App.Current.MainWindow;
            if (mainWindow == null) return;

            var screen = Screen.FromHandle(new WindowInteropHelper(mainWindow).Handle);
            if (subWindow.WindowState== WindowState.Maximized)
            {
                //最大化窗口,固定的彈出到主屏幕,因此需額外處理
                subWindow.Left = screen.Bounds.Left / Dpi.System.FactorX;
                subWindow.Top = screen.Bounds.Top / Dpi.System.FactorY;
            }
            else
            {
                //窗口居中顯示
                subWindow.Left = screen.Bounds.Left / Dpi.System.FactorX + (screen.Bounds.Width / Dpi.System.FactorX - subWindow.Width) / 2;
                subWindow.Top = screen.Bounds.Top / Dpi.System.FactorY + (screen.Bounds.Height / Dpi.System.FactorY - subWindow.Height) / 2;
            }
        }
    }

    public static void SetIsWindowShowInCurrentScreen(DependencyObject element, bool value)
    {
        element.SetValue(IsWindowShowInCurrentScreenProperty, value);
    }

    public static bool GetIsWindowShowInCurrentScreen(DependencyObject element)
    {
        return (bool)element.GetValue(IsWindowShowInCurrentScreenProperty);
    }
}

 

PS:

當窗口狀態為最大化時,即WindowState=“Maximized”,只需要設置位置即可


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()