標籤:tac 最大化 rtu help eof 擷取 change void att
問題:
在多個顯示屏啟動並執行情況下,如果將主視窗從當前顯示屏移動到另一顯示屏。
設定子視窗單例模式,在當前顯示屏時彈出後,在主視窗移動到另一顯示屏後,再彈出子視窗時,你會發現子視窗跑到原來顯示屏去了。
----這是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.Tag?.ToString()==WindowState.Maximized.ToString()) { subWindow.Left = screen.Bounds.Left; subWindow.Top = screen.Bounds.Top; subWindow.Width = screen.Bounds.Width; subWindow.Height = screen.Bounds.Height; } else { subWindow.Left = screen.Bounds.Left + (screen.Bounds.Width - subWindow.Width) / 2; subWindow.Top = screen.Bounds.Top + (screen.Bounds.Height - 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”。是設定不了Location的。那麼就需要去掉Xmal中的WindowState,通過後台去設定全屏
WPF 多屏時子視窗的螢幕位置問題