How to get process handle from process name in C#
By FoxLearn 11/10/2024 3:05:03 AM 62
The `System.Diagnostics.Process` class provides a method called `GetProcessesByName()`, which retrieves all processes with a given name. The parameter passed to this method should be the process's name without the `.exe` extension. Since multiple processes can share the same name, the method returns an array of `Process` objects, potentially containing more than one process instance.
How can we get process handle or process id from running process name in C#?
The `Id` and `Handle` properties in the `Process` class represent the native process ID (PID) and the native handle value, respectively. The `Id` is a unique identifier for the process in the operating system, while the `Handle` is a pointer to the native handle associated with the process.
// To get NOTEPAD.EXE processes var processes = Process.GetProcessesByName("notepad"); foreach (var process in processes) { Console.WriteLine("PID = {0}", process.Id); Console.WriteLine("Process Handle = {0}", process.Handle); }
Using Process.GetProcessesByName(processName) to retrieve
an array of Process
objects that match the given name. If no processes with the specified name are found, it returns an empty array.
Next, Use process.Handle
property of the Process
class gives you a pointer (IntPtr) to the process handle. However, accessing the handle might require elevated privileges depending on the system configuration and the target process.