I am trying to add command-line support for a desktop application I built so that I can run its commands from elsewhere without display the UI. This is approximately what my Main
method looks like:
[STAThread]
private static void Main(string[] args)
{
// Run the desktop application
if (args.Length == 0)
{
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var mainForm = new Form1();
Application.Run(mainForm);
mainForm.BringToFront();
}
// Restart the session and log in console
else if(args[0] == "restartsession")
{
Console.WriteLine("Restarting session...");
}
// argument not recognised (log to console)
else
{
Console.WriteLine($"Argument \"{args[0]}\" not recognised");
}
}
This appears to work just fine, apart from the fact that the Console window is not displayed when calling Console.WriteLine()
.
This is due to my project's output type being set to Windows Application
(I set this in properties). If I change it to Console Application
the console window appears with my logging, but then it also displays when opening the "UI" desktop version (ie running the app without any arguments).
Is there a way to change the output type depending on the arguments passed into Main()
? For example something like this perhaps:
private static void Main(string[] args)
{
if (args.Length == 0)
{
Application.OutputType = WindowsApplication
}
else if(args[0] == "restartsession")
{
Application.OutputType = ConsoleApplication
}
}
I was able to find this link but it appears to be old and not relevant any more. Is there some other way of achieving this?