
在.NET中获取父进程,无需P/Invoke
在.NET中获取父进程是一个常见任务,可以使用平台调用(P/Invoke)方法实现。但是,本文介绍了一种替代方案,无需使用P/Invoke。
此方案利用ntdll.dll库中的NtQueryInformationProcess函数,但它不直接通过P/Invoke与之交互,而是利用ParentProcessUtilities类来抽象该进程。
1 2 3 4 5 6 7 8 9 10 11 | [StructLayout(LayoutKind.Sequential)]
public struct ParentProcessUtilities
{
internal IntPtr Reserved1;
internal IntPtr PebBaseAddress;
internal IntPtr Reserved2_0;
internal IntPtr Reserved2_1;
internal IntPtr UniqueProcessId;
internal IntPtr InheritedFromUniqueProcessId;
}
|
登录后复制
ParentProcessUtilities类包含静态方法,例如GetParentProcess,它接受一个进程句柄并返回表示父进程的Process类的实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public static Process GetParentProcess(IntPtr handle)
{
ParentProcessUtilities pbi = new ParentProcessUtilities();
int returnLength;
int status = NtQueryInformationProcess(handle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength);
if (status != 0)
throw new Win32Exception(status);
try
{
return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32());
}
catch (ArgumentException)
{
return null;
}
}
|
登录后复制
NtQueryInformationProcess函数检索指定进程的基本信息,包括继承的进程ID。通过查询此信息并将其转换为Process实例,此方案允许在托管代码中轻松检索父进程,而无需使用P/Invoke。
以上是如何在不使用P/Invoke的情况下将父进程获取.NET?的详细内容。更多信息请关注PHP中文网其他相关文章!