Search code examples
.netwpfwindowwpf-positioning

Wpf - centering on primary desktop


I know WPF has a "CenterScreen" value for centering a window on the desktop. However, on dual monitor, that is not very pleasant.

How do I center on primary monitor? Do i need to go through the song and dance of detecting the primary desktop, get its geometry, etc, or is there a better way?


Solution

  • Multiple screens are a bit of a problem and it does not have a built in, nicely wrraped way to handle them, but with some math and SystemParameters you can get it done.

    If you position your window at position (0,0) that would be the top left corner of you primary screen. So in order to make your window appear in the center of that screen use:

    this.Left = (SystemParameters.PrimaryScreenWidth / 2) - (this.ActualWidth / 2);
    this.Top = (SystemParameters.PrimaryScreenHeight / 2) - (this.ActualHeight / 2);
    

    The basic idea is simple enough so no need to explain.

    Note this code is for C#, but i am sure VB has something similar.

    Also note you should use the ActualWidth\ActualHeight property and not the Width\Height property as it could hold a NaN value.

    Good luck.