【问题标题】:Check if a specific exe file is running检查特定的 exe 文件是否正在运行
【发布时间】:2018-08-30 21:50:42
【问题描述】:

我想知道如何检查特定位置的程序是否正在运行。例如,在 c:\loc1\test.exe 和 c:\loc2\test.exe 中有两个 test.exe 位置。我只想知道 c:\loc1\test.exe 是否正在运行,而不是 test.exe 的所有实例。

【问题讨论】:

    标签: c# process-management


    【解决方案1】:
    bool isRunning = Process.GetProcessesByName("test")
                    .FirstOrDefault(p => p.MainModule.FileName.StartsWith(@"c:\loc1")) != default(Process);
    

    【讨论】:

    • 很好的答案,虽然 注意 如果您使用类似于 ..StartsWith(new FileInfo(Application.ExecutablePath).DirectoryName) 的东西,它将不起作用。这是因为 DirectoryName 返回带有小写驱动器号的路径,例如 c:。因此,最好将其修改为..FileName.ToLower()..StartsWith(@path.ToLower())
    • 最好进行不区分大小写的比较(例如使用.StartsWith(path, StringComparison.InvariantCultureIgnoreCase)),因为它不涉及改变字符串。
    • 并且,作为一种好的做法,始终使用 OrdinalIgnoreCase 作为文件名等。
    【解决方案2】:

    这是我改进的功能:

    private bool ProgramIsRunning(string FullPath)
    {
        string FilePath =  Path.GetDirectoryName(FullPath);
        string FileName = Path.GetFileNameWithoutExtension(FullPath).ToLower();
        bool isRunning = false;
    
        Process[] pList = Process.GetProcessesByName(FileName);
    
        foreach (Process p in pList) {
            if (p.MainModule.FileName.StartsWith(FilePath, StringComparison.InvariantCultureIgnoreCase))
            {
                isRunning = true;
                break;
            }
        }
    
        return isRunning;
    }
    

    并将其用作:

    ProgramIsRunning(@"c:\loc1\test.exe");
    

    【讨论】:

    • 错误:System.ComponentModel.Win32Exception: 'Access is denied.'
    • @DxTx 尝试以管理员身份运行
    【解决方案3】:

    试试这个...我在启动时使用它来确定另一个进程是否已经在运行与我尝试启动的 exe 同名的进程,然后将其带到前台,(并聚焦)如果它已经在运行...您可以对其进行修改以获取进程名称并测试该特定名称...这将告诉您是否有一个以特定名称运行的进程,但不会告诉您该进程是从哪里加载的... .

    如果有一个进程以指定的名称运行,那么如果该进程有一个公开的可访问方法返回它从哪里加载,你可以在正在运行的进程上调用该方法,否则,我不知道..

    但只是出于好奇,你为什么要关心,除非它们不同?如果它们在某些方面有所不同,则使用该差异(无论是什么)的代码来检测加载的内容。但是,如果它们相同,那么使用哪个磁盘映像来加载它又有什么关系呢?

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);
    
        private const int SW_HIDE = 0;
        private const int SW_SHOWNORMAL = 1;
        private const int SW_SHOWMINIMIZED = 2;
        private const int SW_SHOWMAXIMIZED = 3;
        private const int SW_SHOWNOACTIVATE = 4;
        private const int SW_RESTORE = 9;
        private const int SW_SHOWDEFAULT = 10;
    
     private static bool IsAlreadyRunning()
        {
            // get all processes by Current Process name
            Process[] processes = 
                Process.GetProcessesByName(
                    Process.GetCurrentProcess().ProcessName);
    
            // if there is more than one process...
            if (processes.Length > 1) 
            {
                // if other process id is OUR process ID...
                // then the other process is at index 1
                // otherwise other process is at index 0
                int n = (processes[0].Id == Process.GetCurrentProcess().Id) ? 1 : 0;
    
                // get the window handle
                IntPtr hWnd = processes[n].MainWindowHandle;
    
                // if iconic, we need to restore the window
                if (IsIconic(hWnd)) ShowWindowAsync(hWnd, SW_RESTORE);
    
                // Bring it to the foreground
                SetForegroundWindow(hWnd);
                return true;
            }
            return false;
        }
    

    【讨论】:

      【解决方案4】:

      您应该遍历所有现有进程,然后检查它们的 MainModule 属性以获取您要查找的文件名。像这样的

      using System.Diagnostics;
      using System.IO;
      
      //...
      
      string fileNameToFilter = Path.GetFullPath("c:\\loc1\\test.exe");
      
      foreach (Process p in Process.GetProcesses())
      {
         string fileName = Path.GetFullPath(p.MainModule.FileName);
      
         //cehck for equality (case insensitive)
         if (string.Compare(fileNameToFilter, fileName, true) == 0)
         {
            //matching...
         }
      }
      

      【讨论】:

      【解决方案5】:

      此功能可能会有所帮助:

      using System.Diagnostics;
      
      public bool IsProcessOpen(string name)
      {
          foreach (Process clsProcess in Process.GetProcesses()) {
              if (clsProcess.ProcessName.Contains(name))
              {
                  return true;
              }
          }
          return false;
      } 
      

      来源:http://www.dreamincode.net/code/snippet1541.htm

      【讨论】:

        【解决方案6】:

        类似的东西。 GetMainModuleFileName 有助于从 x86 访问 x64 进程。

          [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;
        }
        

        【讨论】:

          【解决方案7】:

          您可以使用named mutex,它以程序运行所在的目录结构命名。

          【讨论】:

            【解决方案8】:
            System.Reflection.Assembly.GetEntryAssembly()
            

            这会给你带来很多关于入口组装的信息,比如:

            System.Reflection.Assembly.GetEntryAssembly().CodeBase;
            

            这将告诉正在运行的程序集的位置。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-03-16
              • 2013-08-19
              • 1970-01-01
              • 2017-04-03
              • 2015-05-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多