Stella
Stella

Reputation: 548

Close old instance of application

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!

Upvotes: 8

Views: 4393

Answers (3)

Tzah Mama
Tzah Mama

Reputation: 1567

This worked for me

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

Upvotes: 11

TRS
TRS

Reputation: 2097

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

Upvotes: 0

Anuraj
Anuraj

Reputation: 19598

Can you try this code instead of using executable file name to get the Process

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

Upvotes: 0

Related Questions