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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:04:48  来源:igfitidea点击:

Get process name from pid or handle

c#windowsprocesshandles

提问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.GetProcessByIdto get Process. Processhas a lot of information about the running program. Process.ProcessNamegives you the name, Process.MainModule.FileNamegives 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;
        }
    }