How can you determine how the console application was launched?

How can I find out if a user is running my console application by double-clicking the EXE (or shortcut) or by opening a command prompt window and running my console application in this session?

+4
source share
3 answers

Paste this static field into your " Program " class to make sure it works before any exit:

 static bool StartedFromGui = !Console.IsOutputRedirected && !Console.IsInputRedirected && !Console.IsErrorRedirected && Environment.UserInteractive && Environment.CurrentDirectory == System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) && Console.CursorTop == 0 && Console.CursorLeft == 0 && Console.Title == Environment.GetCommandLineArgs()[0] && Environment.GetCommandLineArgs()[0] == System.Reflection.Assembly.GetEntryAssembly().Location; 

This is a bit overwhelming / paranoid, but originates with Explorer, not responding to things like cls && app.exe (by checking the full path) or even cls && "f:\ull\path\to\app.exe" (looking on the headline).

I got the idea from the win32 version of this question .

+8
source

You could figure this out with P / Invoking for the Win32 function GetStartupInfo () .

 [DllImport("kernel32", CharSet=CharSet.Auto)] internal static extern void GetStartupInfo([In, Out] STARTUPINFO lpStartupInfo); 
+1
source

You can find out what is the parent process:

  Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess()?.Parent()?.ProcessName); 

Where Parent () is an extension method, for example:

 public static class Extensions { private static string FindIndexedProcessName(int pid) { var processName = Process.GetProcessById(pid).ProcessName; var processesByName = Process.GetProcessesByName(processName); string processIndexdName = null; for (var index = 0; index < processesByName.Length; index++) { processIndexdName = index == 0 ? processName : processName + "#" + index; var processId = new PerformanceCounter("Process", "ID Process", processIndexdName); if ((int)processId.NextValue() == pid) { return processIndexdName; } } return processIndexdName; } private static Process FindPidFromIndexedProcessName(string indexedProcessName) { var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName); return Process.GetProcessById((int)parentId.NextValue()); } public static Process Parent(this Process process) { return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id)); } } 
0
source

All Articles