代码之家  ›  专栏  ›  技术社区  ›  DotNetSpartan

如何限制用户打开多个exe实例

  •  0
  • DotNetSpartan  · 技术社区  · 6 年前

    我的应用程序在两个版本中作为exe发布-developerbuild和clientbuild(uat)。 developerbuild用于内部开发人员和QA测试,而clientbuild用于最终客户。developerbuild和clientbuild实际上是程序集名称。

    我想限制用户打开多个构建实例。简单来说,用户应该能够打开developerbuild的单个实例。 同时生成一个clientbuild实例, 但不应允许用户同时打开developerbuild或clientbuild的多个实例。

    这是我试过的。下面的代码帮助我维护应用程序的单个实例, 但它不能区分开发人员构建和客户机构建。我希望用户能够同时打开两个构建中的每个实例。

    ///应用程序的入口点

        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();
        }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   pfx RAINA    6 年前

    每个生成的互斥体名称必须是唯一的。因为每个版本都有不同的程序集名称,所以可以将此名称包含在互斥体的名称中,如下所述。

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