WPF 多屏时子窗口的屏幕位置问题
2021-09-17 12:12
标签: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 多屏时子窗口的屏幕位置问题标签:tac 最大化 rtu help eof 获取 change void att 原文地址:http://www.cnblogs.com/kybs0/p/7420767.html
文章标题:WPF 多屏时子窗口的屏幕位置问题
文章链接:http://soscw.com/index.php/essay/107909.html