'Open app always in the center of the display - Windows 11 (WinUi 3)

I am develop a new app for Windows 11 with WinUi 3 and I want when I open the app always open in the center of my screen/display. It is possible?

I am using PInvoke.User32 for set window size (if it helps).

Thank you!



Solution 1:[1]

The following example code is simplistic but achieves what you are asking for.

Create a Windows App SDK project using the blank app template.

In the App.xaml.cs file, change the OnLaunched() method to the following:

m_window = new MainWindow();
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(m_window);
Microsoft.UI.WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
Microsoft.UI.Windowing.AppWindow appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
if (appWindow is not null)
{
    Microsoft.UI.Windowing.DisplayArea displayArea = Microsoft.UI.Windowing.DisplayArea.GetFromWindowId(windowId, Microsoft.UI.Windowing.DisplayAreaFallback.Nearest);
    if (displayArea is not null)
    {
        var CenteredPosition = appWindow.Position;
        CenteredPosition.X = ((displayArea.WorkArea.Width - appWindow.Size.Width) / 2);
        CenteredPosition.Y = ((displayArea.WorkArea.Height - appWindow.Size.Height) / 2);
        appWindow.Move(CenteredPosition);
    }
}
m_window.Activate();

When you run the app, its main window will be centered in the display.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 EddieLotter