简体   繁体   中英

How can i set my WinUI3 program to be started in the center of the screen?

I am currently developing a WinUI3 app, I want to my program starts in the center of the screen. How can i make this happen?

i tried

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();

But it didn't work

Based on Simon's comment I confirmed that this works:

using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using System;
using Windows.Graphics;
using WinRT.Interop;

namespace WinUISamples;

public sealed partial class MainWindow : Window
{
    private bool centered;

    public MainWindow()
    {
        this.InitializeComponent();
        this.Activated += MainWindow_Activated;
    }

    private void MainWindow_Activated(object sender, WindowActivatedEventArgs args)
    {
        if (this.centered is false)
        {
            Center(this);
            centered = true;
        }
    }

    private static void Center(Window window)
    {
        IntPtr hWnd = WindowNative.GetWindowHandle(window);
        WindowId windowId = Win32Interop.GetWindowIdFromWindow(hWnd);

        if (AppWindow.GetFromWindowId(windowId) is AppWindow appWindow &&
            DisplayArea.GetFromWindowId(windowId, DisplayAreaFallback.Nearest) is DisplayArea displayArea)
        {
            PointInt32 CenteredPosition = appWindow.Position;
            CenteredPosition.X = (displayArea.WorkArea.Width - appWindow.Size.Width) / 2;
            CenteredPosition.Y = (displayArea.WorkArea.Height - appWindow.Size.Height) / 2;
            appWindow.Move(CenteredPosition);
        }
    }
}

You also you can just use the WinUIEx NuGet package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM