How do I find out if a process is already running

2019-01-16 13:12发布

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

9条回答
萌系小妹纸
2楼-- · 2019-01-16 13:33

Mnebuerquo wrote:

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.

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:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
 public static extern bool SetForegroundWindow(IntPtr hWnd);
查看更多
欢心
3楼-- · 2019-01-16 13:35

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.

using System;
using System.Diagnostics;
using Microsoft.VisualBasic;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Process[] proc = Process.GetProcessesByName("notepad");
            Interaction.AppActivate(proc[0].MainWindowTitle);
        }
    }
}
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-16 13:42

Two concerns to keep in mind:

  1. Your example involved placing a password on a command line. That cleartext representation of a secret could be a security vulnerability.

  2. 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)?

查看更多
登录 后发表回答