Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you determine how a console application was launched?

How can I tell whether the user launched my console application by double-clicking the EXE (or a shortcut), or whether they already had a command line window open and executed my console app within that session?

like image 500
joshuapoehls Avatar asked Dec 29 '22 08:12

joshuapoehls


2 Answers

Stick this static field in your "Program" class to ensure it runs before any output:

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 little bit overkill/paranoid, but picks up being started from Explorer while not responding to things like cls && app.exe (by checking for the full path) or even cls && "f:\ull\path\to\app.exe" (by looking at the title).

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

like image 101
Fowl Avatar answered Jan 05 '23 01:01

Fowl


You might be able to figure it out by P/Invoking to the Win32 GetStartupInfo() function.

[DllImport("kernel32", CharSet=CharSet.Auto)]
internal static extern void GetStartupInfo([In, Out] STARTUPINFO lpStartupInfo);
like image 27
Mark Cidade Avatar answered Jan 04 '23 23:01

Mark Cidade