命令行参数这样是一种技术,传递一组参数到你希望开始的应用,以某种方式影响它。最普遍的例子就是使用一个具体的文件(如一个编辑器)打开应用。尝试使用Windows自带的记事本,在开始菜单选择运行或者按一下Win+R键,输入:notepad.exe c:\Windows\win.ini。这就在记事本中打开了win.ini文件(记得路径要正确哦)。记事本简单的寻找一条或多条参数,然后使用它们。你的应用也是这样工作的。
通过订阅到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>
我们在这里做的是订阅启动事件,替代了原来的
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的属性,包括一个字符串数组。命令行参数用空格隔开,除非空格是一个引用符。
测试命令行参数
运行上面的例子,什么都不会发生,因为命令行参数已经被指定了。幸好,VS让测试应用变得很容易。在“项目”菜单选择“属性”,点击Debug,你可以定义一个命令行参数。运行后会响应你的参数。
显然这条信息并没什么用。但是,如果你想把它传到主窗口的构造函数里,或者调用一个公共方法,如下:
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();
}
}
}
命令行可能性
这里我们测试了一个准确的参数,作为一个文件名来用。在真实的应用中,可能会有很多参数,甚至有选择的使用它们,譬如切换某个属性的开和关。这样就得使用循环来遍历整个参数列表,这不在我们讨论的范围内。