2011-01-27 120 views
11

假設我已經擁有窗口句柄,我可以使用GetWindowThreadProcessId獲得PID。有沒有一種方法可以獲得進程名稱,而無需獲取所有進程並嘗試匹配我的PID?從pid或句柄獲取進程名稱

回答

15

您可以使用Process.GetProcessById來獲得ProcessProcess有很多關於正在運行的程序的信息。 Process.ProcessName爲您提供了名稱,Process.MainModule.FileName爲您提供了可執行文件的名稱。

+0

是的你是對的。謝謝。我也可以獲得關於這個過程的其他信息。 – user579674 2011-01-27 17:42:55

12
Process.GetProcessById(id).ProcessName 
0

//這是返回任務管理器內存的簡潔方法。如果進程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; 
     } 
    }