WPF和Winform程序在分屏显示时,实现自动选择显示屏并最大化显示

时间:2024-03-25 12:37:04

今天在工作中现场遇到这样的需求,客户有台电脑连接了一个大屏幕和一个显示器,大屏幕显示某个程序,希望在点击运行时,程序自动在大运行并最大化运行。所以做了个测试程序,程序实现了显示在指定屏幕。

  • 引入动态链接库:System.Windows.Form,System.Drawing
  • 需要的类:System.WInfows.Forms.Screen
  • Demo程序的解决方案结构:程序的WPF程序,MainWindow是主窗口

WPF和Winform程序在分屏显示时,实现自动选择显示屏并最大化显示

 

  • 测试说明:我的电脑一共接了三个显示器,所以在界面设计了三个按钮,点击每个按钮分别会将程序显示到不同的屏幕上
  • 主界面

    WPF和Winform程序在分屏显示时,实现自动选择显示屏并最大化显示

    xaml代码:
<Window x:Class="testScreen.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox Margin="10,64,10,10" Name="ls"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="50,26,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="169,26,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click1"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="290,26,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click2"/>

    </Grid>
</Window>
  • 后台代码:
using System.Windows;

namespace testScreen
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }
        System.Windows.Forms.Screen[] sc;
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            sc = System.Windows.Forms.Screen.AllScreens;
            //显示不同屏幕的属性
            foreach (var v in sc)
            {
                ls.Items.Add(v.DeviceName);
                ls.Items.Add(v.Bounds.Width);
                ls.Items.Add(v.Bounds.Height);
            }
        }
  
        //显示在1号屏幕
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.Screen s1 = sc[0];
            System.Drawing.Rectangle r1 = s1.WorkingArea;
            this.Top = r1.Top;
            this.Left = r1.Left;
            this.WindowState = WindowState.Maximized;
        }
        //显示在2号屏幕
        private void Button_Click1(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.Screen s1 = sc[1];
            System.Drawing.Rectangle r1 = s1.WorkingArea;
            this.Top = r1.Top;
            this.Left = r1.Left;
            this.WindowState = WindowState.Maximized;
        }
        //显示在3号屏幕
        private void Button_Click2(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.Screen s1 = sc[2];
            System.Drawing.Rectangle r1 = s1.WorkingArea;
            this.Top = r1.Top;
            this.Left = r1.Left;
            this.WindowState = WindowState.Maximized;
        }
    }
}