Search code examples
c#.netavalonia

How can we change the default shutdown mode of an Avalonia application


Iam trying to build an cross platform desktop application using avalonia(.net 6). Actually Iam new to avalonia. I want to shutdown my application explicitly. The default shutdown mode OnLastWindowClose , I want to change it to OnExplicitShutdown. I got a hint that it want to configure in the Application Lifetime at App axaml.cs . But I don't know how to do it. Anyone please help me. Please give me a detailed description about each and every step to configure it.


Solution

  • You can set it in Main() via StartWithClassicDesktopLifetime(T, string[], ShutdownMode) method.

    EG: In the "Avalonia Application" project template you can set it as follows in Program.cs:

    public static void Main(string[] args) => BuildAvaloniaApp()
        .StartWithClassicDesktopLifetime(args, ShutdownMode.OnExplicitShutdown);
    

    I've also seen it set in OnFrameworkInitializationCompleted() in App.axaml.cs, but I've not tested it...

    public override void OnFrameworkInitializationCompleted()
    {
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            desktop.ShutdownMode = Avalonia.Controls.ShutdownMode.OnExplicitShutdown;
        }
    
        base.OnFrameworkInitializationCompleted();
    }
    

    There is some background information in the Avalonia documentation: Application-lifetimes