Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close old instance of application

Tags:

c#

I'm developing a program, of which only one instance can run. I know I can apply mutex to prevent multiple instances from running.

But I want it so if a new instance of an application runs, it should terminate the old one. The executable will always have the same name.

I've tried running the following on the form load event;

    Process[] pname = Process.GetProcessesByName(AppDomain.CurrentDomain.FriendlyName.Remove(AppDomain.CurrentDomain.FriendlyName.Length - 4));

    if (pname.Length > 1)
    {
        pname[0].Kill();
    }

Which actually works..... once every blue moon. Seriously, it works.. the first time around, the second time the application will simply not load. If I run it about 5 more times it might run.

It doesn't seem too reliable, does anyone perhaps have a more elegant solution?

Thanks!

like image 286
Stella Avatar asked Jun 03 '14 07:06

Stella


1 Answers

This worked for me

if (pname.Length > 1)
{
    pname.Where(p => p.Id != Process.GetCurrentProcess().Id).First().Kill();
}
like image 71
Tzah Mama Avatar answered Sep 23 '22 07:09

Tzah Mama