Monday, January 28, 2019

C#: Allow only one instance of application using mutex

namespace Vurdalakov
{
    using System;
    using System.Security.AccessControl;
    using System.Security.Principal;
    using System.Threading;
    using System.Windows.Forms;

    static class Program
    {
        [STAThread]
        static void Main()
        {
            // Allow everyone to access mutex
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);

            using (var mutex = new Mutex(false, "ApplicationMutex", out Boolean createdNew, securitySettings))
            {
                var isMutextOwned = false;
                try
                {
                    try
                    {
                        isMutextOwned = mutex.WaitOne(500, false);
                        if (!createdNew || !isMutextOwned)
                        {
                            Tracer.Trace("Application is already running, exiting");
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        isMutextOwned = true;
                    }

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    Application.Run(new MainForm());
                }
                catch (Exception ex)
                {
                    // Handle unhandled exception here
                }
                finally
                {
                    if (isMutextOwned)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
    }
}

No comments:

Post a Comment