简体   繁体   English

如何将我的 WinUI3 程序设置为在屏幕中央启动?

[英]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.我目前正在开发一个 WinUI3 应用程序,我希望我的程序在屏幕中央启动。 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.您也可以只使用WinUIEx NuGet 包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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