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

前端 未结 9 827
轻奢々
轻奢々 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:28

    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.

    Use something like this:

    static bool isStillRunning() {
       string processName = Process.GetCurrentProcess().MainModule.ModuleName;
       ManagementObjectSearcher mos = new ManagementObjectSearcher();
       mos.Query.QueryString = @"SELECT * FROM Win32_Process WHERE Name = '" + processName + @"'";
       if (mos.Get().Count > 1)
       {
            return true;
        }
        else
            return false;
    }
    

    NOTE: Add assembly reference "System.Management" to enable the type intellisense.

提交回复
热议问题