Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a process running more than once

Tags:

c#

winforms

I'm working on a my Windows Forms application. I start a calculator process on a button click event using this code:

System.Diagnostics.Process.Start("calc.exe");

If I click the button again, another calculator process is started. So how do I stop the process from running more than once?

Thanks

like image 884
kapil Avatar asked Dec 27 '22 22:12

kapil


2 Answers

Easy... disable the button until the process dies. Of course, you could also put in some kind of logic:

if(!myProcess.HasExited)
{
  alert("You've already started the calculator app.");
}
else
{
  // start the process
}

Personally, I like the former. Just set an event handler and set:

Process.EnableRaisingEvents = true;

The event handler will be raised letting your proggy know when the calculator app has exited, so it can reenable the button.

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.enableraisingevents.aspx

try
{
    myProcess.EnableRaisingEvents = true;
    myProcess.Exited += new EventHandler(myProcess_Exited);
    myProcess.Start();
    // disable button
}
catch()
{
    // enable button
}


private void myProcess_Exited(object sender, System.EventArgs e)
{
    // enable button
}
like image 175
Chris Gessler Avatar answered Jan 08 '23 01:01

Chris Gessler


Make it Simple, Make a function to check if any process is running :

public bool IsProcessOpen(string name)
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName.Contains(name))
{
return true;
}
}
return false;
}

Now use this function where you want to check for the process :

if (!IsProcessOpen("calc"))
 System.Diagnostics.Process.Start("calc.exe");

Update

The process of calculator in newer version of Windows is replaced with Calculator.exe you trying to check if process exist using calc.exe will always fail you need to check for both calc and calculator. Here is screen shot Update

Code

 //If calc.exe or Calculator.exe not exist then start the calculator 
if (!IsProcessOpen("calc")|| !IsProcessOpen("Calculator"))
System.Diagnostics.Process.Start("calc.exe");
like image 24
kakarott Avatar answered Jan 08 '23 00:01

kakarott