Get process name from pid or handle
Asked Answered
R

3

15

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?

Rosetta answered 27/1, 2011 at 17:31 Comment(0)
A
20

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.

Aqaba answered 27/1, 2011 at 17:39 Comment(3)
Yes you are right. Thank you. And I can also get other information too regarding the process.Rosetta
Note that Process.MainModule.Filename fails when called on a 64bit target from an x86 program. ProcessName does not suffer from that limitation.Overactive
@Overactive Do you know if the opposite is true? Like when using a 64bit program to call Process.MainModule.Filename on an x86 target?Cerium
D
14
string name;
using (var p = Process.GetProcessById(id)) { name = p.ProcessName; }
Dolph answered 27/1, 2011 at 17:40 Comment(2)
Process objects are disposable. You need to dispose of the Process.Pilaf
you are right, I updated my answer :)Dolph
L
0

// 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;
        }
    }
Lottielotto answered 13/5, 2016 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.