为了处理命令行参数,需要相应Application.Startup事件。命令行参数是通过StartupEventArgs.Args属性作为字符串数组提供的。
例如:加载一个文档,文档的名称通过命令行参数传递。这种情况下就有必要读取命令行参数作进一步的处理。
C# 代码
public partial class App : Application { private void App_Startup(object sender, StartupEventArgs e) { FileViewer win = new FileViewer(); if (e.Args.Length > 0) { string file = e.Args[0]; if (System.IO.File.Exists(file)) { win.LoadFile(file); } else { } win.Show(); } } }
App.xaml中增加事件
<Application x:Class="Prj显示初始界面.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Startup="App_Startup"> <Application.Resources> </Application.Resources> </Application>
新建名为FileViewer的窗体文件
FileViewer类代码
public void LoadFile(string path)
{
this.Content = File.ReadAllText(path);
this.Title = path;
}