I am looking for the difference between
IntPtr handle_1 = process.Handle;
Gets the native handle of the associated process.
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(
uint processAccess,
bool bInheritHandle,
uint processId
);
IntPtr handle_2 = OpenProcess(0x0010,false,process.Id);
If the function succeeds, the return value is an open handle to the specified process.
Both got different values. But i can still read the memory with those. I would like to understand the difference between those two, to prevent making mistakes. I am using them in the context:
ReadProcessMemory(handle_x, addr, data, data.Length, IntPtr.Zero);
CodePudding user response:
Both are process handles, and as such can be used in the same manner.
A Process
object contains a process handle through its Handle
property. When you call Dispose
on such object, you close that handle.
When you call OpenHandle
on the process' ID, you get a different handle (so it has a different value) that refers to the same process. You must separately close that handle when you're done with it (using the Win32 function CloseHandle
): disposing the Process
object won't magically close the handle you got from OpenProcess
.
So why would you call OpenHandle
when you already have a perfectly functional handle in Process
? Well, access rights, really. The handle obtained by Process
has PROCESS_ALL_ACCESS
(i.e. full access rights). If you want an handle with fewer rights, you can use OpenProcess
for that.
But really, for most purposes, there isn't really a need to mess around with native APIs when you need a process handle.