【发布时间】:2011-06-16 17:25:33
【问题描述】:
假设我已经拥有一个窗口的句柄,我可以使用GetWindowThreadProcessId 获取 PID。有没有一种方法可以获取进程名称,而无需获取所有进程并尝试匹配我的 PID?
【问题讨论】:
标签: c# windows process handles
假设我已经拥有一个窗口的句柄,我可以使用GetWindowThreadProcessId 获取 PID。有没有一种方法可以获取进程名称,而无需获取所有进程并尝试匹配我的 PID?
【问题讨论】:
标签: c# windows process handles
您可以使用Process.GetProcessById 获取Process。 Process 有很多关于正在运行的程序的信息。 Process.ProcessName 为您提供名称,Process.MainModule.FileName 为您提供可执行文件的名称。
【讨论】:
Process.GetProcessById(id).ProcessName
【讨论】:
// 这是一个返回任务管理器内存的简洁小方法。如果进程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;
}
}
【讨论】: