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
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
}
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
Code
//If calc.exe or Calculator.exe not exist then start the calculator
if (!IsProcessOpen("calc")|| !IsProcessOpen("Calculator"))
System.Diagnostics.Process.Start("calc.exe");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With