WPF 启动带参数

两个项目WpfStartupWithArgsDemo(WPF项目)和WpfStartupWithArgsDemo.Console(控制台项目)
启动控制台项目WpfStartupWithArgsDemo.Console,在代码中启动WpfStartupWithArgsDemo,并传递参数

string exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\WpfStartupWithArgsDemo\\bin\\Debug\\WpfStartupWithArgsDemo.exe");
if (File.Exists(exePath))
{
    ProcessStartInfo startInfo = new ProcessStartInfo(exePath, string.Format("{0} {1} {2}", "FirstArg", exePath, 3))
    {
        CreateNoWindow = true,
        UseShellExecute = false
    };

    Process.Start(startInfo);

    Environment.Exit(0);
}

WpfStartupWithArgsDemoStartup事件中接收参数

<Application x:Class="WpfStartupWithArgsDemo.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfStartupWithArgsDemo"
             Startup="App_OnStartup">
</Application>
private void App_OnStartup(object sender, StartupEventArgs e)
{
    ObservableCollection<string> data = new ObservableCollection<string>();
    for (int i = 0; i < e.Args.Length; i++)
    {
        data.Add(e.Args[i]);
        Console.WriteLine(e.Args[i]);
    }
}

示例代码

WpfStartupWithArgsDemo

参考资料

How to start WPF based on Arguments

posted @ 2022-02-09 19:05  Lulus  阅读(803)  评论(0编辑  收藏  举报