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

Posted 唐宋元明清的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF 多屏时子窗口的屏幕位置问题相关的知识,希望对你有一定的参考价值。

问题:

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

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

----这是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 多屏时子窗口的屏幕位置问题的主要内容,如果未能解决你的问题,请参考以下文章

将 XAML 中 WPF 窗口的启动位置更改为右下角

WPF运行中怎么用C# 代码调整窗口位置,特别是怎么居中到屏幕中央

WPF 获取鼠标屏幕位置窗口位置控件位置

wpf仿qq边缘自动停靠,支持多屏

wpf仿qq边缘自动停靠,支持多屏

WPF 窗口居中 & 变更触发机制