How do I find out if a process is already running using c#?

前端 未结 9 786
轻奢々
轻奢々 2020-12-07 23:15

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

相关标签:
9条回答
  • 2020-12-07 23:44

    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);
    
    0 讨论(0)
  • 2020-12-07 23:46

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-07 23:51

    You can use LINQ as well,

    var processExists = Process.GetProcesses().Any(p => p.ProcessName.Contains("<your process name>"));
    
    0 讨论(0)
提交回复
热议问题