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