Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble creating a WPF window in a secondary monitor

I'm working on implementing some Chrome-like tab functionality in an app and am having some trouble getting the new instance to spawn correctly. I've done quite a bit of searching and iterating over various solutions but have not yet been able to make a new window spawn on the second monitor.

Here's the use thread:

  1. Open file
  2. Drag current tab to other monitor
  3. New App instance spawns with that tab set in it, at the location that the user dragged the tab to.

The disconnect is in step 3. The new instance is always spawned on the Primary monitor.

So, some code to expand upon the problem.

namespace app {
    public class AppView {
      public void OpenInNewWindow()
      {
        // Create a new viewmodel
        var appViewModel = new AppVM();

        //// On my machine this returns the correct screen "DISPLAY2".  The Top and Left properties are 0 and 1680, respectively.
        var targetScreen = Screen.FromPoint(System.Windows.Forms.Cursor.Position);

        ////So we can set the position of the new view
        var appView = new AppView(appViewModel);

        //This seats the currently selected data tab inside the new AppViewModel
        RelocateSelectedViewModel(appViewModel);

        appView.WindowStartupLocation = System.Windows.WindowStartupLocation.Manual;
        appView.Top = targetScreen.WorkingArea.Top;
        appView.Left = targetScreen.WorkingArea.Left;
        appView.Show();
        // Have to maximize after we Show() or it won't appera on secondary monitors according to THE INTERNET!
        appView.WindowState = System.Windows.WindowState.Maximized;
        appView.Focus();            
      }
    }
}

I suppose I should mention that I have no problems getting the second Screen. targetScreen in the code above is correctly finding the screen I want, and the Top and Left values of the new window are getting set correctly, to 0 and 1680, respectively. It's just that the AppView.Show() command (which is actually Window.Show()) creates the window on the primary screen.

I have taken this same code to a standalone project and it has worked, which leads me to believe that there is some kind of tie between my new appView and the current one that is overriding my sets here. Has anyone encountered this problem before?

like image 949
Chester Husk Avatar asked Oct 09 '22 08:10

Chester Husk


1 Answers

Did you try using the Winforms Screen.FromControl? See this post.

You can try this hack from this post:

appView.SourceInitialized += (_, __) => appView.WindowState = WindowState.Maximized;
appView.Show();
like image 84
SliverNinja - MSFT Avatar answered Oct 13 '22 11:10

SliverNinja - MSFT