Home > Software engineering >  Is th32ProcessID used in CreateToolhelp32Snapshot a handle
Is th32ProcessID used in CreateToolhelp32Snapshot a handle

Time:09-18

The question is mostly in the title. I am trying to write an example using this method however when I run it with the ALL flag and the handle for a process I get a -1 returned instead of a valid handle to a snapshot and when calling GetLastError I get 2 (The system cannot find the file specified.)

My question is does the th32ProcessID referenced in the MSDN link refer to a normal process handle or is there a different way to get this process ID?

I don't have a great deal of code for this at the moment but what I do have is below:

[DllImport("kernel32", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
internal static extern IntPtr CreateToolhelp32Snapshot([In] SnapshotFlags dwFlags, [In] IntPtr th32ProcessID);

IntPtr Handle = CreateToolhelp32Snapshot(SnapshotFlags.All, ProcessHandle);

Console.WriteLine("ProcessHandle = {0}", ProcessHandle.ToString("X"));
uint flags = 0;
bool result = GetHandleInformation(ProcessHandle, out flags);
Console.WriteLine("Last error = {0} and handle is valid = {1}", WinErrors.GetLastWin32Error(), result);
Console.WriteLine((int)Handle);

CodePudding user response:

A process HANDLE is not the same thing as a process ID. They are not interchangeable.

CreateToolhelp32Snapshot() takes a process ID. And that parameter is a DWORD, so you should be using (u)int (aka (U)Int32), not IntPtr.

GetHandleInformation() takes a process HANDLE.

Since you are passing the wrong type of parameter value to CreateToolhelp32Snapshot(), it is failing, returning INVALID_HANDLE_VALUE, and then GetLastError() is telling you that the specified process ID was not found.

You can get a process HANDLE from a process ID by using OpenProcess().

You can get a process ID from a process HANDLE by using GetProcessId().

  • Related