Shutting down a WPF application from App.xaml.cs

后端 未结 3 1538
谎友^
谎友^ 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: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:

    
        
        
    
    

    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);
        }
    

提交回复
热议问题