【发布时间】:2009-09-16 19:50:54
【问题描述】:
代码中有没有办法检测哪个进程或应用程序启动了我的进程或应用程序。任何 .net、vb6 或 c++ 代码片段都会很棒
【问题讨论】:
-
我推荐的谷歌术语(但没有尝试过):windows find process parent...我的逻辑是Linux维护这个进程的父进程的pid,所以也许windows也这样做。跨度>
代码中有没有办法检测哪个进程或应用程序启动了我的进程或应用程序。任何 .net、vb6 或 c++ 代码片段都会很棒
【问题讨论】:
在 .Net 中,
Assembly.GetEntryAssembly()
返回当前正在运行的程序集进程被启动的程序集。但是如果你有多个进程在运行,我不相信有任何方法可以确定哪个是第一个启动的......
获取入口程序集的版本,
Assembly.GetEntryAssembly().GetName().Version
【讨论】:
您可以以此为基础Taking a Snapshot and Viewing Processes。并一直遍历到根进程!
【讨论】:
James Brown 在他的 “ProcessTree” sn-p 中展示了如何做到这一点:
http://www.catch22.net/content/snippets
虽然代码非常 C-ish,但它非常干净且易于理解。
他基本上是在调用ZwQuerySystemInformation(),它在第二个参数中返回一个SYSTEM_PROCESSES 结构。此结构包含有关过程的信息,包括。一个名为 InheritiedFromProcessId 的成员,它是父进程 ID。
【讨论】:
试试这个:
public class ParentProc {
[DllImport("KERNEL32.dll")] //[DllImport("toolhelp.dll")]
public static extern int CreateToolhelp32Snapshot(uint flags, uint processid);
[DllImport("KERNEL32.DLL")] //[DllImport("toolhelp.dll")]
public static extern int CloseHandle(int handle);
[DllImport("KERNEL32.DLL")] //[DllImport("toolhelp.dll")
public static extern int Process32Next(int handle, ref ProcessEntry32 pe);
[StructLayout(LayoutKind.Sequential)]
public struct ProcessEntry32 {
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)] public string szExeFile;
};
public static Process FindParentProcess() {
int SnapShot = CreateToolhelp32Snapshot(0x00000002, 0); //2 = SNAPSHOT of all procs
try{
ProcessEntry32 pe32 = new ProcessEntry32();
pe32.dwSize = 296;
int procid = System.Diagnostics.Process.GetCurrentProcess().Id;
while(Process32Next(SnapShot, ref pe32) != 0) {
string xname = pe32.szExeFile.ToString();
if(procid==pe32.th32ProcessID) {
return System.Diagnostics.Process.GetProcessById(Convert.ToInt32(pe32.th32ParentProcessID));
}
}
}catch(Exception ex){
throw new Exception(System.Reflection.MethodBase.GetCurrentMethod() + " failed! [Type:"+ex.GetType().ToString()+", Msg:"+ex.Message+"]");
}finally{
CloseHandle(SnapShot);
}
return null;
}
}
【讨论】:
如果性能不是这里的大问题,您也可以使用 WMI,从而保持 100% 托管 (C#/VB.NET)。
示例(仅 WMI 查询,实际 C#/VB.NET 代码省略):
// First get figure the ID of your parent process
SELECT ParentProcessID FROM Win32_Process WHERE ProcessID = <MYPROCESSID>
// Than use that the get any attribute, e.g. the Name, of it
SELECT Name FROM Win32_Process WHERE ProcessID = <PARENTPROCESSID>
【讨论】: