TOC

This article has been localized into Chinese by the community.

WPF應用程式:

WPF 中的命令行参数

命令行参数是一种技术,你可以给一个你想要启动的应用程序传一组参数,以某种方式去影响它。最常见的例子就是让应用程序去打开一个指定的文件,例如,在一个编辑器里打开。你可以用windows内置的Notepad应用程序尝试一下,通过运行(从【开始菜单】中选择 【运行】或按下[Windows键 + R]):

notepad.exe c:\Windows\win.ini

这个会打开Notepad去打开win.ini文件(你可能需要调整一下路径,以对应到你的系统)。Notepad简单的地查找一个或几个参数,然后使用这些参数,你的应用程序也可以这么做。

命令行的参数通过Startup事件(它是我们在App.xaml文章中订阅过的事件)传给你的WPF应用程序,我们会在这个例子中做同样的事情,然后使用这些通过方法参数传进来的值。首先,是App.xaml文件:

<Application x:Class="WpfTutorialSamples.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
			 Startup="Application_Startup">
    <Application.Resources></Application.Resources>
</Application>

我们所做的就是去订阅Startup事件,替换StartupUri属性。然后在App.xaml.cs中实现这个事件。

using System;
using System.Collections.Generic;
using System.Windows;

namespace WpfTutorialSamples
{
	public partial class App : Application
	{

		private void Application_Startup(object sender, StartupEventArgs e)
		{
			MainWindow wnd = new MainWindow();
			if(e.Args.Length == 1)
				MessageBox.Show("Now opening file: \n\n" + e.Args[0]);
			wnd.Show();
		}
	}
}

StartupEventArgs就是我们将用到的东西。它以e为名称,作为参数被传递到应用程序启动事件中。它有一个属性Args,是一个字符串数组。命令行参数通常视空格为分隔,但被引号括起来的字符串中的空格除外。

测试命令行参数

如果你运行上面的例子,不会发生任何变化,因为没有指定任何的命令参数。幸运的是,Visual Studio使得它在你的应用程序中易于测试。从项目菜单选择"[程序名称] 属性"然后进入到Debug页签(你可以在这里定义命令行参数)。这个应该能够看到像这样的内容:

尝试运行一下这个程序,你会看到它对你的参数作出了响应。

当然,消息不是很有帮助。取而代之的是,你可能想把它传给主窗口的构造函数,或者使用它去调用一个公共的open方法,像这样:

using System;
using System.Collections.Generic;
using System.Windows;

namespace WpfTutorialSamples
{
	public partial class App : Application
	{

		private void Application_Startup(object sender, StartupEventArgs e)
		{
			MainWindow wnd = new MainWindow();
			// The OpenFile() method is just an example of what you could do with the
			// parameter. The method should be declared on your MainWindow class, where
			// you could use a range of methods to process the passed file path
			if(e.Args.Length == 1)
				wnd.OpenFile(e.Args[0]);
			wnd.Show();
		}
	}
}

命令行的潜在价值

在本例中,我们测试是否正好有一个参数,如果有,我们就将其用作一个文件名。而在现实世界的例子中,你可能会收集一堆参数,甚至将它们用于选项,例如,打开或关闭某个功能。你可以通过在整个参数列表中进行循环,同时收集你需要进行的信息来做到这一点,不过这已经超出了本文讨论的范围。


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!