Is there a way in code to detect what process or application starts my process or application. Any .net, vb6 or c++ code snips would be great
In .Net,
Assembly.GetEntryAssembly()
returns the assembly that the current running assembly process was kicked off from. But if you have more than one process running, I don't believe there is any way to determine which one was the first one to start up...
to get the version of the entry assembly,
Assembly.GetEntryAssembly().GetName().Version
Try this:
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;
}
}
You can use this as a basis Taking a Snapshot and Viewing Processes. And traverse all the way down to the root process!
James Brown shows in his "ProcessTree" snippet how to do this:
http://www.catch22.net/content/snippets
Although the code is very C-ish it is very clean and good to understand.
He is basically doing a call to ZwQuerySystemInformation()
which returns a SYSTEM_PROCESSES
structure in the second argument. This structure holds information about the process incl. a member called InheritiedFromProcessId
which is the parent processes ID.
If performance is not the big issue here, you could also use WMI and thus stay 100% managed (C#/VB.NET) if you care.
Example (just the WMI queries, actual C#/VB.NET code omitted):
// 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>