命令行参数是一种机制,用户可以在执行时将一组参数或值传递给WPF应用程序.这些参数对于从外部控制应用程序非常重要,例如,如果要从命令提示符打开Word文档,则可以使用此命令" C:\>启动winword word1.docx "它将打开 word1.docx 文档.
命令行参数在启动函数中处理.以下是一个简单示例,说明如何将命令行参数传递给WPF应用程序.让我们创建一个名为 WPFCommandLine 的新WPF应用程序.
从工具箱中拖出一个文本框设计窗口.
在本例中,我们将txt文件路径作为命令行参数传递给我们的应用程序.
程序将读取txt文件,然后在文本框中写下所有文本.
以下XAML代码创建一个文本框并使用一些属性对其进行初始化.
<Window x:Class = "WPFCommandLine.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPFCommandLine" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525"> <Grid> <TextBox x:Name = "textBox" HorizontalAlignment = "Left" Height = "180" Margin = "100" TextWrapping = "Wrap" VerticalAlignment = "Top" Width = "300"/> </Grid> </Window>
现在订阅App.xaml文件中的Startup事件,如下所示.
<Application x:Class = "WPFCommandLine.App" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local = "clr-namespace:WPFCommandLine" StartupUri = "MainWindow.xaml" Startup = "app_Startup"> <Application.Resources> </Application.Resources> </Application>
以下是app.xaml.cs中app_Startup事件的实现,获取命令行参数.
using System.Windows; namespace WPFCommandLine { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public static string[] Args; void app_Startup(object sender, StartupEventArgs e) { // If no command line arguments were provided, don't process them if (e.Args.Length == 0) return; if (e.Args.Length > 0) { Args = e.Args; } } } }
现在,在MainWindow类中,程序将打开txt文件并在文本框上写下所有文本.
如果发现某些错误,然后程序将在文本框上显示错误消息.
using System; using System.IO; using System.Windows; namespace WPFCommandLine { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); String[] args = App.Args; try { // Open the text file using a stream reader. using (StreamReader sr = new StreamReader(args[0])) { // Read the stream to a string, and write // the string to the text box String line = sr.ReadToEnd(); textBox.AppendText(line.ToString()); textBox.AppendText("\n"); } } catch (Exception e) { textBox.AppendText("The file could not be read:"); textBox.AppendText("\n"); textBox.AppendText(e.Message); } } } }
当编译并执行上面的代码时,它将生成一个带有文本框的空白窗口,因为该程序需要一个命令行参数.因此,Visual Studio提供了一种使用命令行参数执行应用程序的简便方法.
右键单击解决方案资源管理器中的WPF项目并选择属性,它将显示以下窗口.
选择Debug选项并在命令行参数中写入文件路径.
使用Test.txt创建一个txt文件,并在该文件中写入一些文本并将其保存在任何位置.在这种情况下,txt文件保存在" D:\ "硬盘上.
保存项目中的更改并立即编译和执行您的应用程序.您将在TextBox中看到程序从Text.txt文件中读取的文本.
现在让我们尝试将您机器上的文件名从 Test.txt 更改为 Test1.txt 然后再次执行你的程序,然后你会在文本框中看到错误信息.
我们建议您执行上述代码并按照所有步骤成功执行应用程序.