<p>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.</p>

<p>So how in C# would I so this in the example below?</p>

<pre><code>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(); 
}
</code></pre>

[{'answer_id': 51149, 'author': 'DaveK', 'author_id': 4244, 'author_profile': 'https://Stackoverflow.com/users/4244', 'pm_score': 6, 'selected': True, 'text': '<p>This should do it for ya.</p>\n\n<p><a href="http://www.dreamincode.net/code/snippet1541.htm" rel="noreferrer">Check Processes</a></p>\n\n<pre><code>//Namespaces we need to use\nusing System.Diagnostics;\n\npublic bool IsProcessOpen(string name)\n{\n    //here we\'re going to get a list of all running processes on\n    //the computer\n    foreach (Process clsProcess in Process.GetProcesses()) {\n        //now we\'re going to see if any of the running processes\n        //match the currently running processes. Be sure to not\n        //add the .exe to the name you provide, i.e: NOTEPAD,\n        //not NOTEPAD.EXE or false is always returned even if\n        //notepad is running.\n        //Remember, if you have the process running more than once, \n        //say IE open 4 times the loop thr way it is now will close all 4,\n        //if you want it to just close the first one it finds\n        //then add a return; after the Kill\n        if (clsProcess.ProcessName.Contains(name))\n        {\n            //if the process is found to be running then we\n            //return a true\n            return true;\n        }\n    }\n    //otherwise we return a false\n    return false;\n}\n\n</code>\n</pre>\n'}, {'answer_id': 51151, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': '<p>You can simply enumerate processes using <a href="http://msdn.microsoft.com/en-us/library/1f3ys1f9.aspx" rel="nofollow noreferrer">Process.GetProcesses</a> method.</p>\n'}, {'answer_id': 51154, 'author': 'jmatthias', 'author_id': 2768, 'author_profile': 'https://Stackoverflow.com/users/2768', 'pm_score': 1, 'selected': False, 'text': "<p>I think the complete answer to your problem requires understanding of what happens when your application determines that an instance of foo.exe is already running i.e what does '//TODO: Switch to foo.exe process' actually mean?</p>\n"}, {'answer_id': 51155, 'author': 'Gulzar Nazim', 'author_id': 4337, 'author_profile': 'https://Stackoverflow.com/users/4337', 'pm_score': 3, 'selected': False, 'text': '<p>I have used the AppActivate function in VB runtime to activate an existing process.\nYou will have to import Microsoft.VisualBasic dll into the C# project.</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\nusing Microsoft.VisualBasic;\n\nnamespace ConsoleApplication3\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process[] proc = Process.GetProcessesByName("notepad");\n            Interaction.AppActivate(proc[0].MainWindowTitle);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 51173, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 5, 'selected': False, 'text': '<p>You can use LINQ as well,</p>\n\n<pre><code>var processExists = Process.GetProcesses().Any(p =&gt; p.ProcessName.Contains("&lt;your process name&gt;"));\n</code></pre>\n'}, {'answer_id': 51181, 'author': 'Mnebuerquo', 'author_id': 5114, 'author_profile': 'https://Stackoverflow.com/users/5114', 'pm_score': 1, 'selected': False, 'text': '<p>In a past project I needed to prevent multiple execution of a process, so I added a some code in the init section of that process which creates a named mutex. This mutext was created and acquired before continuing the rest of the process. If the process can create the mutex and acquire it, then it is the first one running. If another process already controls the mutex, then the one which fails is not the first so it exits immediately. </p>\n\n<p>I was just trying to prevent a second instance from running, due to dependencies on specific hardware interfaces. Depending on what you need with that "switch to" line, you might need a more specific solution such as a process id or handle.</p>\n\n<p>Also, I had source code access to the process I was trying to start. If you can not modify the code, adding the mutex is obviously not an option.</p>\n'}, {'answer_id': 51189, 'author': 'csjohnst', 'author_id': 1292, 'author_profile': 'https://Stackoverflow.com/users/1292', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>Mnebuerquo wrote: </p>\n  \n  <blockquote>\n    <p>Also, I had source code access to the\n    process I was trying to start. If you\n    can not modify the code, adding the\n    mutex is obviously not an option.</p>\n  </blockquote>\n</blockquote>\n\n<p>I don\'t have source code access to the process I want to run. </p>\n\n<p>I have ended up using the proccess MainWindowHandle to switch to the process once I have found it is alread running:</p>\n\n<pre><code>[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern bool SetForegroundWindow(IntPtr hWnd);\n</code></pre>\n'}, {'answer_id': 51222, 'author': 'Jay Bazuzi', 'author_id': 5314, 'author_profile': 'https://Stackoverflow.com/users/5314', 'pm_score': 1, 'selected': False, 'text': '<p>Two concerns to keep in mind:</p>\n\n<ol>\n<li><p>Your example involved placing a\npassword on a command line.  That\ncleartext representation of a secret\ncould be a security vulnerability.</p></li>\n<li><p>When enumerating processes, ask\nyourself which processes you really\nwant to enumerate.  All users, or\njust the current user?  What if the\ncurrent user is logged in twice (two\ndesktops)?</p></li>\n</ol>\n'}, {'answer_id': 23824382, 'author': 'Israel Ocbina', 'author_id': 1990838, 'author_profile': 'https://Stackoverflow.com/users/1990838', 'pm_score': 2, 'selected': False, 'text': '<p>I found out that Mutex is not working like in the Console application. So using WMI to query processes that can be seen using Task Manager window will solved your problem.</p>\n\n<p>Use something like this:</p>\n\n<pre><code>static bool isStillRunning() {\n   string processName = Process.GetCurrentProcess().MainModule.ModuleName;\n   ManagementObjectSearcher mos = new ManagementObjectSearcher();\n   mos.Query.QueryString = @"SELECT * FROM Win32_Process WHERE Name = \'" + processName + @"\'";\n   if (mos.Get().Count &gt; 1)\n   {\n        return true;\n    }\n    else\n        return false;\n}\n</code></pre>\n\n<p>NOTE: Add assembly reference "System.Management" to enable the type intellisense.</p>\n'}]
['https://Stackoverflow.com/questions/51148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1292/']