How to force WPF startup window to specific screen?

前端 未结 2 1291
北荒
北荒 2020-12-31 16:42

I have a WPF application that will show information on a projector through a dedicated window. I would like to configure what screen to be used for projector display and wha

2条回答
  •  抹茶落季
    2020-12-31 16:55

    The accepted answer no longer works on Windows 10 with per-monitor DPI in the app’s manifest.

    Here’s what worked for me:

    public partial class MyWindow : Window
    {
        readonly Rectangle screenRectangle;
    
        public MyWindow( System.Windows.Forms.Screen screen )
        {
            screenRectangle = screen.WorkingArea;
            InitializeComponent();
        }
    
        [DllImport( "user32.dll", SetLastError = true )]
        static extern bool MoveWindow( IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint );
    
        protected override void OnSourceInitialized( EventArgs e )
        {
            base.OnSourceInitialized( e );
            var wih = new WindowInteropHelper( this );
            IntPtr hWnd = wih.Handle;
            MoveWindow( hWnd, screenRectangle.Left, screenRectangle.Top, screenRectangle.Width, screenRectangle.Height, false );
        }
    
        void Window_Loaded( object sender, RoutedEventArgs e )
        {
            WindowState = WindowState.Maximized;
        }
    }
    

    Just setting Left/Top doesn’t work. Based on my tests, per-monitor DPI awareness only kicks in after window is already created and placed on some monitor. Before that, apparently Left/Top properties of the window scale with DPI of the primary monitor.

    For some combinations of per-monitor DPI and monitors layout, this caused a bug where setting Left/Top properties to the pixels values of System.Windows.Forms.Screen rectangle caused the window to be positioned somewhere else.

    The above workaround is only suitable for maximizing, it does not always sets the correct size of the window. But at least it sets correct top-left corner which is enough for the maximize to work correctly.

提交回复
热议问题