I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it.
So how in C# would I so this in the example below?
using System.Diagnostics;
...
Process foo = new Process();
foo.StartInfo.FileName = @"C:\bar\foo.exe";
foo.StartInfo.Arguments = "Username Password";
bool isRunning = //TODO: Check to see if process foo.exe is already running
if (isRunning)
{
//TODO: Switch to foo.exe process
}
else
{
foo.Start();
}
I don't have source code access to the process I want to run.
I have ended up using the proccess MainWindowHandle to switch to the process once I have found it is alread running:
I have used the AppActivate function in VB runtime to activate an existing process. You will have to import Microsoft.VisualBasic dll into the C# project.
Two concerns to keep in mind:
Your example involved placing a password on a command line. That cleartext representation of a secret could be a security vulnerability.
When enumerating processes, ask yourself which processes you really want to enumerate. All users, or just the current user? What if the current user is logged in twice (two desktops)?