Wpf start in primary screen

前端 未结 5 1278
臣服心动
臣服心动 2020-12-21 00:43

If user has multiple screens,

how can I start application in primary screen or chosen screen at start up

5条回答
  •  执念已碎
    2020-12-21 01:42

    This is my purely WPF solution to center a Window on the primary monitor with a border of empty space around it (because I don't want it maximized). My setup is a square-ish monitor on my left and a widescreen on my right. This was tested with each monitor being set as the primary monitor in Windows.

    Before I get to that solution, there are three useful properties on System.Windows.SystemParameters that give various heights. The numbers given are for my 1920x1080 widescreen.

    • PrimaryScreenHeight - 1080. The actual resolution height set in Windows.
    • WorkArea.Height - 1040. The actual resolution height minus the Start Bar
    • FullPrimaryScreenHeight - 1018. The actual resolution minus the Start Bar and minus the Window header.

    This is my solution and I use WorkArea.Height:

        protected T SetWindowLocation(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;
        }
    

提交回复
热议问题