WPF多屏显示

WPF多屏显示

实现代码

需要在分屏显示的窗体

<Window x:Class="WpfClient.Tools.FrmSubScreen"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WpfClient.Tools"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="FrmSubScreen"
        Width="800"
        Height="450"
        AllowsTransparency="True"
        Background="Transparent"
        ResizeMode="NoResize"
        ShowInTaskbar="False"
        Topmost="True"
        WindowStartupLocation="CenterScreen"
        WindowStyle="None"
        mc:Ignorable="d">
    <Grid>
        <Image Grid.Column="1"       Source="https://img.alicdn.com/imgextra/i2/4179999320/O1CN01CIIi2C2IibyZZrMHw_!!0-item_pic.jpg_430x430q90.jpg" Stretch="Fill" />
    </Grid>
</Window>

需要在分屏显示的窗体后台代码

public partial class FrmSubScreen : Window
    {
        public FrmSubScreen()
        {
            InitializeComponent();
            this.Loaded += (s, e) => 
            {
                foreach (Screen scr in Screen.AllScreens)
                {
                    if (!scr.Primary)
                    {
                        //设置窗体位置
                        WindowStartupLocation = WindowStartupLocation.Manual;
                        Left = scr.WorkingArea.Left;
                        Top = scr.WorkingArea.Top;
                        WindowState = WindowState.Maximized;
                        break;
                    }
                }
            };
        }
    }

让窗体在分屏显示的代码

public class SecondaryScreen
    {
        public static void Display()
        {
            var screens = Screen.AllScreens;
            if (Screen.AllScreens.Count()>=2)
            {
                Dispatcher.CurrentDispatcher.Invoke(()=> 
                {
                    try
                    {
                        FrmSubScreen subScreen = new FrmSubScreen();

                        subScreen.Show();
                    }
                    catch (Exception e)
                    {
                        Logger.Default.Error(e.Message,e.StackTrace);
                    }
                });
            }           
        }
    }

实现原理

假设屏幕分辨率是1920*1080,有两屏幕,多屏的情况下主屏的左上角的坐标为(0,0),第二个屏幕左上角坐标是(1920,0)。双屏显示就是让窗体自动偏移到指定的屏幕中。

例如:

Left = scr.WorkingArea.Left;
Top = scr.WorkingArea.Top;

注意事项

需要特别注意:Window.WindowState属性的设置,如果在Xaml代码中直接设置最大化,那么无论后续如何设置分屏窗口都会直接显示在主屏幕中。

解决方案:

在Loaded时设置WindowState = WindowState.Maximized

登峰造极的成就源于自律
原文地址:https://www.cnblogs.com/fishpond816/p/14292841.html