WPF中的命令行参数(转载)

命令行参数这样是一种技术,传递一组参数到你希望开始的应用,以某种方式影响它。最普遍的例子就是使用一个具体的文件(如一个编辑器)打开应用。尝试使用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">//注意这里,原来的key是 StartupUri
    <Application.Resources></Application.Resources>
</Application>

事件名称是’Startup’,而不是’StartupUri’(即一个属性)。正确订阅处理程序:‘Startup =“Application_Startup”’ – ASh
我们在这里做的是订阅启动事件,替代了原来的 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();
                }
        }
}

命令行可能性
这里我们测试了一个准确的参数,作为一个文件名来用。在真实的应用中,可能会有很多参数,甚至有选择的使用它们,譬如切换某个属性的开和关。这样就得使用循环来遍历整个参数列表,这不在我们讨论的范围内。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值