Search code examples
c#handlepid

GetProcessId returning zero


I've got an array full of process handles, and am now trying to obtain the relevant process IDs for each of them.

However, all my Process Ids are coming back as zero. Anyone able to point out what obvious issue I am missing ?

Many Thanks

The 'child' array is populated with process Id's thus :

currChild = FindWindowEx(hParent, prevChild, null, null);

Then I try to get the process ID:

for (int i = 0; i < children.Count; ++i)
 {
      handle = children[i];
      pid = GetProcessId(handle);
      Console.WriteLine(children[i].ToString("X") + " : " + pid.ToString());

APIs :

[DllImport("user32.dll", EntryPoint = "FindWindowEx", CharSet = CharSet.Auto)]
   static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("kernel32.dll", EntryPoint = "GetProcessId", CharSet = CharSet.Auto)]
    static extern int GetProcessId(IntPtr handle);

Output:

2417E2 : 0
B20D9A : 0
48108C : 0
8809D6 : 0
B5140E : 0
4207F6 : 0
4213B0 : 0
5D15DA : 0
etc ....

Solution

  • Note that GetProcessId accepts as input a process handle, not a window handle For the latter, you can use GetWindowThreadProcessId instead.

    See GetWindowThreadProcessId