You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WinUI 3中设置应用默认启动为全屏?能否在启动时调用指定函数?

解决WinUI3应用默认全屏启动的问题

你提供的代码如下:

namespace MyApp
{
    public sealed partial class MainWindow : Window
    {
        AppWindow m_appWindow;
        
        public MainWindow()
        {
            this.InitializeComponent();
            m_appWindow = GetAppWindowForCurrentWindow();
        }
               
        private AppWindow GetAppWindowForCurrentWindow()
        {
            IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
            WindowId myWndId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
                    
            return AppWindow.GetFromWindowId(myWndId);
        }

        private void SwitchPresenter_FullScreen(object sender, RoutedEventArgs e)
        {
            m_appWindow.SetPresenter(AppWindowPresenterKind.FullScreen);
        }  
    }
}

可以在应用启动时调用全屏设置,有两种可靠的实现方式:

方法一:在MainWindow构造函数中直接调用

修改构造函数,在获取m_appWindow后直接执行全屏设置逻辑,代码如下:

public MainWindow()
{
    this.InitializeComponent();
    m_appWindow = GetAppWindowForCurrentWindow();
    // 启动时直接设置全屏
    m_appWindow.SetPresenter(AppWindowPresenterKind.FullScreen);
}

方法二:通过窗口Loaded事件调用(更稳妥)

如果构造函数中直接调用出现窗口未就绪的问题,可以绑定窗口的Loaded事件,在窗口完全加载完成后再设置全屏:

  1. 在XAML的Window标签中添加Loaded事件绑定:
<Window
    x:Class="MyApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MyApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Loaded="MainWindow_Loaded">
    <!-- 窗口内容 -->
</Window>
  1. 在代码后台实现事件处理函数:
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    m_appWindow.SetPresenter(AppWindowPresenterKind.FullScreen);
}

两种方法都能实现应用启动即全屏的效果,推荐第二种方法,它能确保窗口已经完成初始化和加载,避免潜在的异常。

内容的提问来源于stack exchange,提问作者BillJobs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 11:45:28