# Is it possible to determine which process starts my .Net application?

I am developing console application in .Net and I want to change a behavior a little based on information that application was started from cmd.exe or from explorer.exe. Is it possible?

-

Process this_process = Process.GetCurrentProcess();
int parent_pid = 0;
using (ManagementObject MgmtObj = new ManagementObject("win32_process.handle='" + this_process.Id.ToString() + "'"))
{
MgmtObj.Get();
parent_pid = Convert.ToInt32(MgmtObj["ParentProcessId"]);
}
string parent_process_name = Process.GetProcessById(parent_pid).ProcessName;

-
Please check Adam Mitz comment bellow. I still found this answer the best because of simplicity. However someone should concern. –  Jakub Šturc Sep 10 '08 at 10:01

The CreateToolhelp32Snapshot Function has a Process32First method that will allow you to read a PROCESSENTRY32 Structure. The structure has a property that will get you the information you want:

th32ParentProcessID - The identifier of the process that created this process (its parent process).

http://www.codeproject.com/KB/cs/IsApplicationRunning.aspx

-

One issue with the ToolHelp/ManagementObject approaches is that the parent process could already have exited.

The GetStartupInfo Win32 function (use PInvoke if there's no .NET equivalent) fills in a structure that includes the window title. For a Win32 console application "app.exe", this title string is "app" when started from cmd and "c:\full\path\to\app.exe" when started from explorer (or the VS debugger).

Of course this is a hack (subject to change in other versions, etc.).

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
int main()
{
STARTUPINFO si;
GetStartupInfo(&si);
MessageBox(NULL, si.lpTitle, NULL, MB_OK);
return 0;
}

-
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.25532037019729614, "perplexity": 7262.714123832199}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2015-35/segments/1440645338295.91/warc/CC-MAIN-20150827031538-00129-ip-10-171-96-226.ec2.internal.warc.gz"}