1

I have WPF application and i want to add the option to do my stuff in commend line instead of open the GUI.

Any way to send my Application exe arguments and in case the arguments length in > 0 continue with command line instead of open the GUI ?

user979033
  • 5,430
  • 7
  • 32
  • 50

2 Answers2

3

You could edit the App.xaml.cs file and override the OnStartup method:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        string[] args = e.Args;
        if(args.Length > 0 && args[0] == "cl")
        {
            //...
        }
        else
        {
            base.OnStartup(e);
            Window2 mainWindow = new Window2();
            mainWindow.Show();
        }
    }
}

You should also remove the StartupUri attribute from <Application> root element of the App.xaml file.

But if you want to be able to write to the console you need to create a console window manually:

No output to console from a WPF application?

Then you might as well create a console application in Visual Studio and instead start your WPF application based on the command line argument(s), e.g.:

public class Program
{
    public static void Main(string[] args)
    {
        if (args.Length == 0 || args[0] != "cl")
        {
            System.Diagnostics.Process.Start(@"c:\yourWpfApp.exe");
        }
        else
        {
            //...
        }
    }
}

A console application is not a WPF application and vice versa. So create two different applications.

mm8
  • 163,881
  • 10
  • 57
  • 88
1

In your App.xaml.cs implement the OnStartup method. So you can access the arguments passed via command line.

protected override void OnStartup(StartupEventArgs e)
{
    var args = e.Args;
    // do anything with arguments
}
S. Spindler
  • 546
  • 3
  • 12