【问题标题】:Get process name from pid or handle从 pid 或句柄获取进程名称
【发布时间】:2011-06-16 17:25:33
【问题描述】:

假设我已经拥有一个窗口的句柄,我可以使用GetWindowThreadProcessId 获取 PID。有没有一种方法可以获取进程名称,而无需获取所有进程并尝试匹配我的 PID?

【问题讨论】:

    标签: c# windows process handles


    【解决方案1】:

    您可以使用Process.GetProcessById 获取ProcessProcess 有很多关于正在运行的程序的信息。 Process.ProcessName 为您提供名称,Process.MainModule.FileName 为您提供可执行文件的名称。

    【讨论】:

    • 是的,你是对的。谢谢你。我还可以获得有关该过程的其他信息。
    • 请注意,当从 x86 程序在 64 位目标上调用 Process.MainModule.Filename 时会失败。 ProcessName 不受此限制。
    • @EricLaw 你知道是否相反吗?就像使用 64 位程序在 x86 目标上调用 Process.MainModule.Filename 时一样?
    【解决方案2】:
    Process.GetProcessById(id).ProcessName
    

    【讨论】:

      【解决方案3】:

      // 这是一个返回任务管理器内存的简洁小方法。如果进程id不存在,则会抛出异常并为内存返回0

          /// <summary>
          /// Gets the process memory.
          /// </summary>
          /// <param name="processId">The process identifier.</param>
          /// <returns></returns>
          /// <para> </para>
          /// <para> </para>
          /// <exception cref="ArgumentException"> </exception>
          /// <exception cref="ArgumentNullException"> </exception>
          /// <exception cref="ComponentModel.Win32Exception"> </exception>
          /// <exception cref="InvalidOperationException"> </exception>
          /// <exception cref="PlatformNotSupportedException"> </exception>
          /// <exception cref="UnauthorizedAccessException"> </exception>
          public static long GetProcessMemory(int processId)
          {
              try
              {
                  var instanceName = Process.GetProcessById(processId).ProcessName;
      
                  using (var performanceCounter = new PerformanceCounter("Process", "Working Set - Private", instanceName))
                  {
                      return performanceCounter.RawValue / Convert.ToInt64(1024);
                  }
              }
              catch (Exception)
              {
                  return 0;
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2015-03-07
        • 1970-01-01
        • 2010-09-09
        • 1970-01-01
        • 2012-01-22
        • 2010-10-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多