是否可以通过进程句柄获取进程对象?
Is it possible to get a Process object by process handle?
通过 winapi 调用启动进程时(例如 CreateProcessAsUserW
),您将获得一个进程和线程句柄。有了这个,您可以获得进程的 PID,然后您可以进行 Process.GetProcessById
调用。但是,当进程已经同时终止时,此调用将失败。
有没有办法通过句柄获取 Process
对象?
我现在正在使用 GetExitCodeProcess
至少获得 一些 信息,但我宁愿 return 具有相关属性集的 Process
对象。
我通过执行以下操作“解决”了问题:
// Construct Process object through private constructor, taking the PID. This also works when the process has already exited.
Process new_process = Activator.CreateInstance(typeof(Process), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { ".", false, (int)pid, null }, null, null) as Process;
// Wrap the handle and give ownership to wrapper
SafeProcessHandle safe_handle = new SafeProcessHandle((IntPtr)process_handle, true);
// Set interal process handle for Process object through private method. This prevents the .ExitCode accessor to throw an exception.
typeof(Process).GetMethod("SetProcessHandle", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(new_process, new object[] { safe_handle });
这可行,但不是很好。因为它通过反射访问了两个私有函数。有关 Process 对象内部结构的更多信息,请查看 here.
通过 winapi 调用启动进程时(例如 CreateProcessAsUserW
),您将获得一个进程和线程句柄。有了这个,您可以获得进程的 PID,然后您可以进行 Process.GetProcessById
调用。但是,当进程已经同时终止时,此调用将失败。
有没有办法通过句柄获取 Process
对象?
我现在正在使用 GetExitCodeProcess
至少获得 一些 信息,但我宁愿 return 具有相关属性集的 Process
对象。
我通过执行以下操作“解决”了问题:
// Construct Process object through private constructor, taking the PID. This also works when the process has already exited.
Process new_process = Activator.CreateInstance(typeof(Process), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { ".", false, (int)pid, null }, null, null) as Process;
// Wrap the handle and give ownership to wrapper
SafeProcessHandle safe_handle = new SafeProcessHandle((IntPtr)process_handle, true);
// Set interal process handle for Process object through private method. This prevents the .ExitCode accessor to throw an exception.
typeof(Process).GetMethod("SetProcessHandle", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(new_process, new object[] { safe_handle });
这可行,但不是很好。因为它通过反射访问了两个私有函数。有关 Process 对象内部结构的更多信息,请查看 here.