C # Method with two different types of behavior, which he named, although the application "Launch" or "Command Line"
I want to develop a method that, when called through the running application, should print a list, but when the method is called using the CommandLine, I want it to print the same list in a txt file.
Do you guys know how I can do this check, or if theres a way to detect where the process is being called from?
I found this post on Stack Overflow, but I cannot figure out how I can solve my problem.
source to share
You can try to capture the console window from a kernel 32 function call.
private const string Kernel32_DllName = "kernel32.dll";
[DllImport(Kernel32_DllName)]
private static extern IntPtr GetConsoleWindow();
public static bool HasConsole {
get { return GetConsoleWindow() != IntPtr.Zero; }
}
HasConsole should return true if there is a console loaded, false if launched from a window.
If the program is a console application, the console window will always be open, so detecting the startup method will be more difficult.
There is an SO question covering this already - How can you determine how the console application was started?
As a quick reference, the relevant section is below, but I would recommend reading this thread as it explains the process more clearly.
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;
source to share