Get process name from pid or handle

好久不见. 提交于 2021-02-08 12:22:25

问题


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?


回答1:


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.




回答2:


Process.GetProcessById(id).ProcessName



回答3:


// 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

    /// <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;
        }
    }


来源:https://stackoverflow.com/questions/4819750/get-process-name-from-pid-or-handle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!