Check if a specific exe file is running

后端 未结 8 1935
野趣味
野趣味 2020-12-01 04:44

I want to know how i can check a program in a specific location if it is running. For example there are two locations for test.exe in c:\\loc1\\test.exe and c:\\loc2\\test.e

8条回答
  •  渐次进展
    2020-12-01 04:55

    Something like this. GetMainModuleFileName helps to access x64 process from x86.

      [DllImport("kernel32.dll")]
      public static extern bool QueryFullProcessImageName(IntPtr hprocess, int dwFlags, StringBuilder lpExeName, out int size);
    
      private bool CheckRunningProcess(string processName, string path) {
    
      Process[] processes = Process.GetProcessesByName(processName);
      foreach(Process p in processes) {
        var name = GetMainModuleFileName(p);
        if (name == null)
          continue;
        if (string.Equals(name, path, StringComparison.InvariantCultureIgnoreCase)) {
          return true;
        }
      }
      return false;
    }
    
    // Get x64 process module name from x86 process
    private static string GetMainModuleFileName(Process process, int buffer = 1024) {
    
      var fileNameBuilder = new StringBuilder(buffer);
      int bufferLength = fileNameBuilder.Capacity + 1;
      return QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, out bufferLength) ?
          fileNameBuilder.ToString() :
          null;
    }
    

提交回复
热议问题