如果用户有多个屏幕,如何在启动时在主屏幕或选择的屏幕上启动应用程序?
using System;
using System.Windows;
using System.Windows.Forms;
namespace Foo
{
public class WindowUtility
{
public static void MoveToMonitor(Window window, int monitorId, bool maximize)
{
Screen[] screens = Screen.AllScreens;
int screenId = monitorId - 1;
if (screens.Length > 1 && screenId < screens.Length)
{
var screen = screens[screenId];
var area = screen.WorkingArea;
if (maximize)
{
window.Left = area.Left;
window.Top = area.Top;
window.Width = area.Width;
window.Height = area.Height;
}
else
{
window.Left = area.Left;
window.Top = area.Top;
}
}
}
}
}
protected T SetWindowLocation<T>(T window) where T : Window
{
//This function will set a window to appear in the center of the user's primary monitor.
//Size will be set dynamically based on resoulution but will not shrink below a certain size nor grow above a certain size
//Desired size constraints. Makes sure window isn't too small if the users monitor doesn't meet the minimum, but also not too big on large monitors
//Min: 1024w x 768h
//Max: 1400w x 900h
const int absoluteMinWidth = 1024;
const int absoluteMinHeight = 768;
const int absoluteMaxWidth = 1400;
const int absoluteMaxHeight = 900;
var maxHeightForMonitor = System.Windows.SystemParameters.WorkArea.Height - 100;
var maxWidthForMonitor = System.Windows.SystemParameters.WorkArea.Width - 100;
var height = Math.Min(Math.Max(maxHeightForMonitor, absoluteMinHeight), absoluteMaxHeight);
var width = Math.Min(Math.Max(maxWidthForMonitor, absoluteMinWidth), absoluteMaxWidth);
window.Height = height;
window.Width = width;
window.Left = (System.Windows.SystemParameters.FullPrimaryScreenWidth - width) / 2;
window.Top = (System.Windows.SystemParameters.FullPrimaryScreenHeight - height) / 2;
window.WindowStartupLocation = WindowStartupLocation.Manual;
return window;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Width = SystemParameters.PrimaryScreenWidth / 2;
Height = SystemParameters.PrimaryScreenHeight / 2;
Left = (SystemParameters.PrimaryScreenWidth - Width) / 2;
Top = (SystemParameters.PrimaryScreenHeight - Height) / 2;
}