WPF mutex for single app instance not working

前端 未结 7 1757
梦谈多话
梦谈多话 2020-12-30 01:24

I\'m trying to use the mutex method for only allowing one instance of my app to run. That is - I only want a max of one instance for all users on a machine. I\'ve read throu

7条回答
  •  再見小時候
    2020-12-30 02:18

    Here is my new code which has the answer provided by @Willem van Rumpt (and @OJ)...

    public partial class App : Application
    {
        private Mutex _instanceMutex = null;
    
        protected override void OnStartup(StartupEventArgs e)
        {
            // check that there is only one instance of the control panel running...
            bool createdNew;
            _instanceMutex = new Mutex(true, @"Global\ControlPanel", out createdNew);
            if (!createdNew)
            {
                _instanceMutex = null;
                Application.Current.Shutdown();
                return;
            }
    
            base.OnStartup(e);
        }
    
        protected override void OnExit(ExitEventArgs e)
        {          
            if(_instanceMutex != null)
                _instanceMutex.ReleaseMutex();
            base.OnExit(e);
        }
    }
    

提交回复
热议问题