简体   繁体   中英

Prevent multiple windows application instances

I have an application which can be used in 2 different ways, depending on whether I pass an argument to the main or not. With the following sample code I can:

- Start multiple instances, each with arguments 参数
- Start one instance without arguments

static void Main(string[] args)
{
     string mutexName = "";
     if (args.Length > 0)
     {
         mutexName = args[0];
     } else 
     {
         mutexName = "NoArgs";
     }

     using (Mutex appMutex = new Mutex(false, String.Format("{0}-{1}", mutexName, appGuid)))
     {
         if (!appMutex.WaitOne(0, false))
         {
             MessageBox.Show("Instance already running");
             return;
         }

         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new Form1());
     }
 }

Works perfectly! But I would also want applications with arguments and no arguments be mutually exluded. As in.. If one or more applications with arguments are open, you cannot start one without arguments, and vice versa, if a program without args is open, you cannot start any program with args.

Does anybody have an idea of how I can accomplish this? I've tried different ways with the mutex and I'm starting to think that this cannot be done with Mutexes. Or I'll need "group" mutexes or something.

You're saying that if a NoArgs application is launched, no other application can be launched. So check this firsthand.

Then:

  • If you're launching your application without args, you can start only if there is no application launched.
  • If you're launching your application with args, you can launch it if the application has not been launched with a mutex of the same name.

You can't determine with a mutex if there is a remaining application already launched. For this, you need a counting mutex , also called a semaphore . You may use a semaphore to determine the number of applications launched. Then, you need a mutex for the "NoArgs" case, the mutex for each argument-passed mutex name, and a semaphore to count successfully launched applications.

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