Search code examples
c#.netwinformsprocesspid

How can I get the PID of the parent process of my application


My winform application is launched by another application (the parent), I need determine the pid of the application which launch my application using C#.


Solution

  • WMI is the easier way to do this in C#. The Win32_Process class has the ParentProcessId property. Here's an example:

    using System;
    using System.Management;  // <=== Add Reference required!!
    using System.Diagnostics;
    
    class Program {
        public static void Main() {
            var myId = Process.GetCurrentProcess().Id;
            var query = string.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", myId);
            var search = new ManagementObjectSearcher("root\\CIMV2", query);
            var results = search.Get().GetEnumerator();
            results.MoveNext();
            var queryObj = results.Current;
            var parentId = (uint)queryObj["ParentProcessId"];
            var parent = Process.GetProcessById((int)parentId);
            Console.WriteLine("I was started by {0}", parent.ProcessName);
            Console.ReadLine();
        }
    }
    

    Output when run from Visual Studio:

    I was started by devenv