I am trying to create a WPF application that takes command line arguments. If no arguments are given, the main window should pop up. In cases of some specific command line arguments, code should be run with no GUI and exit when finished. Any suggestions on how this should properly be done would be appreciated.
+24
A:
First, find this attribute at the top of your App.xaml file and remove it:
StartupUri="Window1.xaml"
That means that the application won't automatically instantiate your main window and show it.
Next, override the OnStartup method in your App class to perform the logic:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if ( /* test command-line params */ )
{
/* do stuff without a GUI */
}
else
{
new Window1().ShowDialog();
}
this.Shutdown();
}
Matt Hamilton
2009-01-08 23:13:48
Can you interact with the console (Console.ReadLine/WriteLine) at that point?
Kieran Benton
2009-11-16 10:33:22
Certainly you can call Console.WriteLine, but the output won't appear on the console from which you launched the app. I'm not sure what "Console" is in the context of a WPF application.
Matt Hamilton
2009-11-18 01:55:45
In order to write to the console in which the app was launched, you need to call AttachConsole(-1), Console.Writeline(message), and then FreeConsole() when you're done.
oltman
2010-04-05 20:19:15
Bam. Thanks for this answer. Perfect for my situation.
WernerCD
2010-09-25 02:34:07
+2
A:
To check for the existence of your argument - in Matt's solution use this for your test:
e.Args.Contains("MyTriggerArg")
GeekyMonkey
2009-08-13 14:05:55