无法从GetProcessId(.. hWnd)中提取processID(pInvoke)

Gra*_*ant 2 c# pinvoke automation process handle

即时通讯使用以下方法

    [DllImport("kernel32.dll", SetLastError=true)]
    static extern int GetProcessId(IntPtr hWnd);
Run Code Online (Sandbox Code Playgroud)

尝试获取正在运行的进程的processId,我唯一的信息是HWND.我的问题是它始终返回错误代码6,即ERROR_INVALID_HANDLE.我以为我可能会将参数更改为int类型,但也没有用.我无法枚举正在运行的进程,因为任何时候都可能有多个实例在运行.

谁能看出我做错了什么?

注意:该进程是从暴露给框架的自动化对象中生成的,只提供HWND属性.也许还有另一种方法来获取processID,因为我编写的代码首先负责运行它?

我的代码看起来与此类似......

AutomationApplication.Application extApp = new AutomationApplication.Application(); extApp.Run(); ...

Rog*_*mbe 11

给定进程句柄而不是窗口句柄时,GetProcessId获取进程ID.它实际上是:

[DllImport("kernel32", SetLastError = true)]
static extern int GetProcessId(IntPtr hProcess);
Run Code Online (Sandbox Code Playgroud)

如果你有一个窗口句柄,那么你想要GetWindowThreadProcessId函数:

[DllImport("user32")]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
Run Code Online (Sandbox Code Playgroud)

这将返回线程ID,并将进程ID放在out-param中.