Shutting down a WPF application from App.xaml.cs

后端 未结 3 1486
谎友^
谎友^ 2020-12-08 18:51

I am currently writing a WPF application which does command-line argument handling in App.xaml.cs (which is necessary because the Startup event seems to be the recommended w

相关标签:
3条回答
  • 2020-12-08 19:46

    If you remove the StartupUri from app.xaml for an application with a MainWindow you need to make sure you make the following call in your OnStartup method otherwise the application will not terminate when your MainWindow closes.

    this.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
    

    @Frank Schwieterman, something along these lines may help you with your console window issue.

    0 讨论(0)
  • 2020-12-08 19:51

    I did this a little differently to avoid having to set the StartupUri and ShutdownMode properties. First edit the App.xaml file and replace StartupUri with Startup:

    <Application x:Class="Menu.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Menu"
             Startup="Application_Startup">
        <Application.Resources>
        </Application.Resources>
    </Application>
    

    Then add Application_Startup to the code along with OnExit:

    public partial class App : Application
    {
        private volatile static Mutex s_mutex;
    
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            s_mutex = new Mutex(true, @"Global\MenuMutex", out bool grantedOwnership);
    
            if (!grantedOwnership)
            {
                MessageBox.Show($"Another instance is already running!", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                Current.Shutdown();
            }
            else
                new MainWindow().Show();
        }
    
        protected override void OnExit(ExitEventArgs e)
        {
            s_mutex?.ReleaseMutex();
            s_mutex?.Dispose();
            s_mutex = null;
            base.OnExit(e);
        }
    
    0 讨论(0)
  • 2020-12-08 19:54

    First remove the StartupUri property from App.xaml and then use the following:

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
    
            bool doShutDown = ...;
    
            if (doShutDown)
            {
                Shutdown(1);
                return;
            }
            else
            {
                this.StartupUri = new Uri("Window1.xaml", UriKind.Relative);
            }
        }
    
    0 讨论(0)
提交回复
热议问题