简体   繁体   中英

How to restrict user from opening more than one instance of the exe

My Application is released as exe in two build versions - DeveloperBuild and ClientBuild(UAT). The DeveloperBuild is meant for internal developers and QA Testing while ClientBuild is for end customers. 'DeveloperBuild' and 'ClientBuild' are actually the assembly names.

I want to restrict user from opening more than one instance of the build.In simple words, User should be able to open single instance of DeveloperBuild and single instance of ClientBuild simultaneously, BUT user should not be allowed to open more than one instance of the DeveloperBuild or ClientBuild at the same time.

This is what I've tried. The below code helps me to maintain the single instance of my application, But it does not distinguish between Developer Build and Client Build. I want user to have an advantage to open single instance each of both the builds simultaneously.

/// The Entry point to the application

    protected override void OnStartup(StartupEventArgs e)
    {           
        const string sMutexUniqueName = "MutexForMyApp";

        bool createdNew;

        _mutex = new Mutex(true, sMutexUniqueName, out createdNew);

        // App is already running! Exiting the application  
        if (!createdNew)
        {               
            MessageBox.Show("App is already running, so cannot run another instance !","MyApp",MessageBoxButton.OK,MessageBoxImage.Exclamation);
            Application.Current.Shutdown();
        }

        base.OnStartup(e);

        //Initialize the bootstrapper and run
        var bootstrapper = new Bootstrapper();
        bootstrapper.Run();
    }

The mutex name must be unique per build. Because you have different assembly names for each version, you can include this name in the name of your mutex, as done here below.

protected override void OnStartup(StartupEventArgs e)
{           
    string sMutexUniqueName = "MutexForMyApp" + Assembly.GetExecutingAssembly().GetName().Name;

    bool createdNew;

    _mutex = new Mutex(true, sMutexUniqueName, out createdNew);

    // App is already running! Exiting the application  
    if (!createdNew)
    {               
        MessageBox.Show("App is already running, so cannot run another instance !","MyApp",MessageBoxButton.OK,MessageBoxImage.Exclamation);
        Application.Current.Shutdown();
    }

    base.OnStartup(e);

    //Initialize the bootstrapper and run
    var bootstrapper = new Bootstrapper();
    bootstrapper.Run();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM