设置WPF应用程序的显示(译文)
By S.F.
本文链接 https://www.kyfws.com/news/setting-the-display-for-a-wpf-application/
版权声明 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
- 2 分钟阅读 - 989 个词 阅读量 0设置WPF应用程序的显示(译文)
原文地址:https://www.codeproject.com/Articles/469034/Setting-the-Display-for-a-WPF-Application
原文作者:Joel Ivory Johnson
译文由本站翻译
前言
设置WPF应用程序的显示
我正在做一个演示项目,我需要为其设置运行WPF应用程序集的显示.总共有6个WPF应用程序将同时在同一台计算机上运行.每个应用程序都将在不同的显示器上运行.我以为我会分享我用来控制此应用程序的每个实例转到哪个显示的解决方案. 我要做的第一件事是检索有关计算机有多少个显示器以及每个显示器的坐标的信息.计算机创建一个(逻辑)显示器,并映射每个显示设备以覆盖此逻辑显示器上的一系列坐标.因此,我需要检索显示列表以及将其映射到的坐标.可用于执行此操作的类在System.Windows.Forms库中.由于我不是在制作Windows Forms应用程序,所以我不想添加一个using指令,该指令将包含整个库.如果这样做的话,在该名称空间和我使用的WPF名称空间中都将存在一些类名称,这可能会导致某些解析问题.因此,我仅包括名称空间中的单个类.
using Screen=System.Windows.Forms.Screen
“屏幕"类包含一个名为"全部"屏幕的成员,该成员包含"屏幕"对象的集合,这些对象在每个屏幕上提供了信息.如果您想制作一个显示所有屏幕及其位置的简单WPF程序,则只需几行代码.以下是此类程序的后台代码和XAML.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = Screen.AllScreens;
}
}
<Window x:Class="ScreenTest.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 ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding DeviceName}" />
<TextBlock Grid.Column="1" Text="{Binding WorkingArea.X}" />
<TextBlock Grid.Column="2" Text="{Binding WorkingArea.Y}" />
<TextBlock Grid.Column="3" Text="{Binding WorkingArea.Width}" />
<TextBlock Grid.Column="4" Text="{Binding WorkingArea.Height}" />
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
对于将要运行的程序,我已经在配置文件中为该程序的预期显示设置了设备名称.第一个显示的典型显示名称是” \.\ DISPLAY1".我已经制作了一种方法,该方法将采用所需的显示名称,尝试查找它,并相应地设置窗口的位置和大小.
void SetTargetDisplay()
{
var targetDeviceName = Settings.Default.DisplayDevice;
if(!String.IsNullOrEmpty(targetDeviceName))
{
// see if the device name specified exists here. It's possible
// this was configured to run on a different machine and the
// configured device might not exists
var screen = (from s in Screen.AllScreens
where s.DeviceName.ToLower().Equals(targetDeviceName.ToLower())
select s).FirstOrDefault();
if (screen != null)
{
Left = screen.WorkingArea.Left;
Top = screen.WorkingArea.Top;
Width = screen.WorkingArea.Width;
Height = screen.WorkingArea.Height;
}
}
}
如果显示不存在(可能由于印刷错误或为另一台机器配置了程序而发生),则该方法将忽略该请求.
许可
本文以及所有相关的源代码和文件均已获得The Code Project Open License (CPOL)的许可。
WPF 新闻 翻译