Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi what I'm trying to do is to detect my application Number 1 if it's running using my application number 2 using mutex but it is not working for me it always opening an another application


Check my code

Mutex mutex = new Mutex(false, "ediSystem.exe");
try
{
    if (mutex.WaitOne(0, false))
    {
        Process notePad = new Process();
        notePad.StartInfo.FileName = "ediSystem.exe";
        notePad.Start();
        mutex.ReleaseMutex();
    }
    else
    {
        MessageBox.Show("notepad Already Running!");
    }
}
finally
{
    if (mutex != null)
    {
        mutex.Close();
        mutex = null;
    }
}


What I have tried:

i tried a different approach but i think i'm doing it wrong.

int intInstances = CountInstances();

           if (intInstances <= 1)
           {

              // Application.Run(new Form1());
               Process notePad = new Process();
               notePad.StartInfo.FileName = "notepad.exe";
               notePad.Start();
               //mutex.ReleaseMutex();
           }
           else
           {
               MessageBox.Show("Another instance of this program is already running.Close other instance first", "Already running", MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
               Application.Exit();
           }



private static int CountInstances()
        {
            string[] strAppLoc = Assembly.GetExecutingAssembly().Location.Split("\\".ToCharArray());
            string strAppName = strAppLoc[strAppLoc.Length - 1];
            string strProcessQuery = "select name from CIM_Process where name = '" + "notepad.exe" + "'";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(strProcessQuery);
            int intCountInstances = 0;
            foreach (ManagementObject item in searcher.Get())
            {
                intCountInstances++;

                if (intCountInstances > 1)
                break;
            }
            return intCountInstances;
        }
Posted
Updated 2-Dec-20 22:12pm

1 solution

According to the Mutex[^] documentation, you can use a third parameter to determine if the Mutex already exists and allow you to exit the application if it is the case. Something similar to:
C#
var mutex = new Mutex(true, "myapplication", out bool created);

if (!created) {
  // The application is already running
}
 
Share this answer
 
Comments
BillWoodruff 3-Dec-20 22:45pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900