WPF 应用程序命令行参数而不是启动 GUI

WPF application command line arguments instead of start GUI

我有 WPF 应用程序,我想添加在推荐行中执行我的操作的选项,而不是打开 GUI

有什么方法可以发送我的 Application exe arguments 以防万一 arguments length in > 0 继续 command line 而不是打开 GUI ?

在您的 App.xaml.cs 中实施 OnStartup 方法。因此您可以访问通过命令行传递的参数。

protected override void OnStartup(StartupEventArgs e)
{
    var args = e.Args;
    // do anything with arguments
}

您可以编辑 App.xaml.cs 文件并覆盖 OnStartup 方法:

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();
        }
    }
}

您还应该从 App.xaml 文件的 <Application> 根元素中删除 StartupUri 属性。

但是如果您希望能够写入控制台,您需要手动创建一个控制台window:

No output to console from a WPF application?

那么您不妨在 Visual Studio 中创建一个控制台应用程序,而不是根据命令行参数启动您的 WPF 应用程序,例如:

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

控制台应用程序不是 WPF 应用程序,反之亦然。所以创建两个不同的应用程序。