Search code examples
wpfcommand-line

WPF application command line arguments instead of starting GUI


I have WPF application and I want to add the option to do my stuff on the command line instead of opening the GUI.

Is there a way to get the command line arguments in my application and in case there are arguments continue without opening the GUI?


Solution

  • 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.