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.

C #: is it possible that one application behaves like a console or windows application depending on switches?

+3


source to share


2 answers


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;

      

+2


source


Hey you could try this to determine if you are working from console or not bool runningFromConsole = Console.OpenStandardInput(1) != Stream.Null;



0


source







All Articles