WPF mutex for single app instance not working

前端 未结 7 1642
梦谈多话
梦谈多话 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:11

    As extension sample:

    public static class Extension
    {
        private static Mutex mutex;
    
        public static bool IsOneTimeLaunch(this Application application, string uniqueName = null)
        {
            var applicationName = Path.GetFileName(Assembly.GetEntryAssembly().GetName().Name);
            uniqueName = uniqueName ?? string.Format("{0}_{1}_{2}",
                Environment.MachineName,
                Environment.UserName,
                applicationName);
    
            application.Exit += (sender, e) => mutex.Dispose();
            bool isOneTimeLaunch;
            mutex = new Mutex(true, uniqueName, out isOneTimeLaunch);
            return isOneTimeLaunch;
        }
    }
    

    App Class:

        protected override void OnStartup(StartupEventArgs e)
        {
            if (this.IsOneTimeLaunch())
            {
                base.OnStartup(e);
            }
            else
            {
                this.Shutdown();
            }
        }
    

提交回复
热议问题