windows 从 pid 或 handle 获取进程名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4819750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get process name from pid or handle
提问by user579674
Assuming I already have the handle to a window, I can get the PID with GetWindowThreadProcessId
. Is there a way I can get the process name without having to get all the processes and try to match my PID?
假设我已经有了一个窗口的句柄,我可以用GetWindowThreadProcessId
. 有没有一种方法可以获取进程名称而不必获取所有进程并尝试匹配我的 PID?
回答by detunized
You can use Process.GetProcessById
to get Process
. Process
has a lot of information about the running program. Process.ProcessName
gives you the name, Process.MainModule.FileName
gives you the name of the executable file.
您可以使用Process.GetProcessById
获取Process
. Process
有很多关于正在运行的程序的信息。 Process.ProcessName
给你名字,Process.MainModule.FileName
给你可执行文件的名字。
回答by A.Baudouin
Process.GetProcessById(id).ProcessName
回答by puffgroovy
// Here is a neat little method to return the task manager memory. If the process id doesn't exist, it will throw an exception and return 0 for the memory
// 这是返回任务管理器内存的一个巧妙的小方法。如果进程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;
}
}