【问题标题】:GetProcessId returning zeroGetProcessId 返回零
【发布时间】:2015-01-15 14:22:27
【问题描述】:

我有一个充满进程句柄的数组,现在我正在尝试获取每个进程句柄的相关进程 ID。

但是,我的所有进程 ID 都归零。 谁能指出我遗漏了什么明显的问题?

非常感谢

“子”数组由进程 ID 填充,因此:

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

然后我尝试获取进程ID:

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

API:

[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);

输出:

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

【问题讨论】:

  • 你的程序有足够的权限吗?尝试使用管理权限运行它
  • 什么是handle?什么是children
  • 在 pinvoke 时检查错误绝不是可选的,您没有友好的 .NET 异常来避免麻烦。 GetProcessId() 通过返回 0 指示失败。修复您的 pinvoke 声明并添加 SetLastError = true。并在收到失败指示时抛出 Win32Exception。现在发现程序中的错误变得很容易。
  • 汉斯,感谢您的提示...我会添加软管:)

标签: c# handle pid


【解决方案1】:

注意GetProcessId 接受一个进程句柄作为输入,而不是一个窗口句柄 对于后者,您可以改用GetWindowThreadProcessId

GetWindowThreadProcessId

【讨论】:

  • 马顿,你说得对。这是多么蹩脚的错误。也许休息一下,喝杯咖啡,揉揉我的眼球会有所帮助。感谢您的回复。
  • @user3379697 是的,有时正确的解决方案就是打个盹 30 分钟。
猜你喜欢
  • 1970-01-01
  • 2021-09-23
  • 2016-11-24
  • 2021-10-24
  • 2017-11-19
  • 2015-01-23
  • 2016-11-24
  • 2013-12-04
  • 2010-12-31
相关资源
最近更新 更多