检测哪个进程/程序启动我的进程/程序

时间:2009-09-16 19:50:54

标签: c# .net c++ vb6

代码中是否有办法检测哪个进程或应用程序启动了我的进程或应用程序。任何.net,vb6或c ++代码都会很棒

5 个答案:

答案 0 :(得分:1)

在.Net,

Assembly.GetEntryAssembly() 

返回当前正在运行的程序集进程从中启动的程序集。但如果你有多个进程在运行,我不相信有任何方法可以确定哪一个是第一个启动...

获取条目程序集的版本,

 Assembly.GetEntryAssembly().GetName().Version

答案 1 :(得分:1)

您可以将此作为基础Taking a Snapshot and Viewing Processes。并一直遍历到根进程!

答案 2 :(得分:1)

James Brown在他的“ProcessTree”片段中展示了如何执行此操作:

http://www.catch22.net/content/snippets

虽然代码非常C-ish但它非常干净且易于理解。

他基本上正在调用ZwQuerySystemInformation(),它在第二个参数中返回SYSTEM_PROCESSES结构。该结构保存有关过程的信息。名为InheritiedFromProcessId的成员,它是父进程ID。

答案 3 :(得分:0)

试试这个:

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; 
} 

}

答案 4 :(得分:0)

如果性能不是这里的大问题,那么你也可以使用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>
相关问题