如何让UWP AppWindow进入全屏模式?

How to make UWP AppWindow enter full screen mode?

我正在使用 AppWindow 为应用程序创建多个 windows,我希望用户能够 windows 全屏,但是 ApplicationView.TryEnterFullScreenMode 不起作用,它在 AppWindow.

中使用时一直 returns false

Sample code 来自微软文档:

private void ToggleFullScreenModeButton_Click(object sender, RoutedEventArgs e)
{
    var view = ApplicationView.GetForCurrentView();
    if (view.IsFullScreenMode)
    {
        view.ExitFullScreenMode();
    }
    else
    {
        view.TryEnterFullScreenMode(); // Returns false in an AppWindow
    }
}

如何让 AppWindow 进入全屏模式?

对于 AppWindow 你应该使用 AppWindowPresenter.RequestPresentation 并传递 AppWindowPresentationKind.FullScreen 作为参数。

我提出的解决方案(基于 this answer)使用以下方法处理退出全屏模式:

  • 原始按钮。
  • 标题栏中的返回 window 按钮。
  • 退出键。

XAML:

<Button x:Name="ToggleFullScreenButton" Text="Full screen mode" Click="ToggleFullScreenButton_Click" />

后面的代码:

public AppWindow AppWindow { get; } // This should be set to the AppWindow instance.

private void ToggleFullScreenButton_Click(object sender, RoutedEventArgs e)
{
    var configuration = AppWindow.Presenter.GetConfiguration();
    if (FullScreenButton.Text == "Exit full screen mode" && _tryExitFullScreen())
    {
        // Nothing, _tryExitFullScreen() worked.
    }
    else if (AppWindow.Presenter.RequestPresentation(AppWindowPresentationKind.FullScreen))
    {
        FullScreenButton.Text = "Exit full screen mode";

        _ = Task.Run(async () =>
        {
            await Task.Delay(500); // Delay a bit as AppWindow.Changed gets fired many times on entering full screen mode.
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                AppWindow.Changed += AppWindow_Changed;
                this.KeyDown += Page_KeyDown;
            });
        });
    }
}

private bool _tryExitFullScreen()
{
    if (AppWindow.Presenter.RequestPresentation(AppWindowPresentationKind.Default))
    {
        FullScreenButton.Text = "Full screen mode";
        AppWindow.Changed -= AppWindow_Changed;
        this.KeyDown -= Page_KeyDown;
        return true;
    }

    return false;
}

// handles the back-to-window button in the title bar
private void AppWindow_Changed(AppWindow sender, AppWindowChangedEventArgs args)
{
    if (args.DidSizeChange) // DidSizeChange seems good enough for this
    {
        _tryExitFullScreen();
    }
}

// To make the escape key exit full screen mode.
private void Page_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Escape)
    {
        _tryExitFullScreen();
    }
}