WPF Command Line

前端 未结 4 1770
谎友^
谎友^ 2020-11-27 12:32

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 a

4条回答
  •  情话喂你
    2020-11-27 13:21

    A combination of the above solutions, for .NET 4.0+ with output to the console:

    [DllImport("Kernel32.dll")]
    public static extern bool AttachConsole(int processID);
    
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
    
        if (e.Args.Contains("--GUI"))
        {
            // Launch GUI and pass arguments in case you want to use them.
            new MainWindow(e).ShowDialog();
        }
        else
        {
            //Do command line stuff
            if (e.Args.Length > 0)
            {
                string parameter = e.Args[0].ToString();
                WriteToConsole(parameter);
            }
        }
        Shutdown();
    }
    
    public void WriteToConsole(string message)
    {
        AttachConsole(-1);
        Console.WriteLine(message);
    }
    

    Alter the constructor in your MainWindow to accept arguments:

    public partial class MainWindow : Window
    {
        public MainWindow(StartupEventArgs e)
        {
            InitializeComponent();
        }
    }
    

    And don't forget to remove:

    StartupUri="MainWindow.xaml"
    

提交回复
热议问题