Close the old application instance

I am developing a program from which only one instance can work. I know that I can use mutex to prevent multiple instances from starting.

But I want that if a new instance of the application starts, it must interrupt the old one. The executable will always have the same name.

I tried to run the following in the form load event;

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

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

What actually works ..... once every blue moon. Seriously, this works .. the first time, the second time the application just does not load. If I run it another 5 times, it may work.

It does not seem too reliable, maybe someone has a more elegant solution?

Thank!

+4
source share
3 answers

It worked for me

if (pname.Length > 1)
{
    pname.Where(p => p.Id != Process.GetCurrentProcess().Id).First().Kill();
}
+5

, Process

Process currentProcess = Process.GetCurrentProcess();
Process[] processItems = Process.GetProcessesByName(currentProcess.ProcessName);
+1

You can change your logic. Why not call Environment.Exit when starting another instance based on the pname condition. Length == 1

0
source

Source: https://habr.com/ru/post/1543017/


All Articles