1

I want to add command line options to my WPF application but in case command line is sent into my EXE file i don't want the UI open but only command line options. Is it possible to do something like this ?

public partial class MainWindow : MetroWindow
{
    public MainWindow()
    {
        string[] args = Environment.GetCommandLineArgs();
        if (args.Length > 1)
        {
            this.Hide();
            ParseArgs(args);
        }
        else
        {
            InitializeComponent();
        }
    }

    private void ParseArgs(string[] args)
    {
        // bla bla
    }
}
berry wer
  • 637
  • 2
  • 12
  • 25

2 Answers2

0

This Replacing WPF entry point is what you want to do.

In there you can get the command line arguments and decide if you want to show the main window or not.

If you need to write output that is shown in the command line when the application is run, you need to do something like this :

Right click on the project, "Properties", "Application" tab, change "Output Type" to "Console Application", and then it will also have a console.

However, once you do that then you will have a console window pop up even if you start the application not from a command line. There is no way to have it both ways - either the application is a command line application which can launch a window, or it is a window application which cannot write to the console which started it. It is a limitation in Windows - the bit that decides it is in the PE header.

This question discusses this point in great detail, and offers several hacks to achieve what you want.

You might want to actually search for your problems, because I count at least 5 SO questions dedicated to this (new) topic already.

Community
  • 1
  • 1
user3690202
  • 3,844
  • 3
  • 22
  • 36
  • And any case to return string and print like in console application ? – berry wer Aug 17 '15 at 16:13
  • Ah, you didn't say you needed to do console output - that is a different problem. I'll adjust my answer to get you started in the right direction for that problem. – user3690202 Aug 17 '15 at 16:15
  • So the best option is to add console application project into my solution and than i will have 2 separate exe files ?? – berry wer Aug 17 '15 at 16:25
  • Again, you have changed the topic quite a bit, but I will update the answer to another reference on Stack Overflow which deals with this exact same new question. – user3690202 Aug 17 '15 at 16:29
0

You should do this in your app.xaml.

I explain :

You put an application startup method handler(instead of using the startup uri). Here you can parse the cl arguments and then set StartupUri = MainWindow.xaml which will open your window. and if you won't open main window then you don't set startup uri.

  • here you are : http://stackoverflow.com/questions/13425425/how-to-customize-startup-of-wpf-application you can google it if you need more samples though – Jacques Martin Aug 17 '15 at 16:29