I am trying to make it so that if another instance of my program is running, it should close down the instance that's already running and start the new instance. I currently tried this:
[STAThread]
static void Main()
{
Mutex mutex = new System.Threading.Mutex(false, "supercooluniquemutex");
try
{
if (mutex.WaitOne(0, false))
{
// Run the application
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new fMain());
}
else
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Equals(Process.GetCurrentProcess().ProcessName) && proc.Id != Process.GetCurrentProcess().Id)
{
proc.Kill();
break;
}
}
// Run the application
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new fMain());
}
}
finally
{
if (mutex != null)
{
mutex.Close();
mutex = null;
}
}
}
But for some reason it doesn't kill the already running instance, it just kills itself most of the time and sometimes it doesn't do anything at all.
What do I do to get this to work?
EDIT: I know the usual way of doing it is showing a message that the application is already running, but in this application it is vital that it kills the old process instead of showing a message.