您的位置:首页 > 其它

WPF 多屏时子窗口的屏幕位置问题

2017-08-23 23:16 441 查看
设置多屏时窗口居中显示

问题:

在多个显示屏运行的情况下,如果将主窗口从当前显示屏移动到另一显示屏。

设置子窗口单例模式,在当前显示屏时弹出后,在主窗口移动到另一显示屏后,再弹出子窗口时,你会发现子窗口跑到原来显示屏去了。

----这是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”,只需要设置位置即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: