WPF系列教程(二十一):Application类的任务

项目源码

显示初始界面

例如我们在打开一个应用程序的初始阶段,打开第一个窗口之前,一般会显示该程序的某个图标页面,显得比较专业。
在项目中右键添加现有项,把一张图片添加进来:
在这里插入图片描述
设置图片属性-生成操作为开始界面:
在这里插入图片描述
这样在窗体出现之前会显示该图片,大约300ms。

处理命令行参数

以下例子为加载一个文档:
在项目中添加一个txt文档。
在这里插入图片描述
属性-复制到输出目录-始终复制
在这里插入图片描述

在这里插入图片描述
点击项目-属性-调试,填入文档的名称。
在这里插入图片描述
删除APP.xaml文件中的StartupUri="MainWindow.xaml",添加事件属性
在这里插入图片描述
不用XAML文件中的startupuri来启动应用程序,而是自己编写了启动时的响应程序:

private void App_Startup(object sender, StartupEventArgs e)
{
    
    
    MainWindow window = new MainWindow();
    if (e.Args.Length > 0)  // 有命令行参数文件
    {
    
    
        string file = e.Args[0];
        if (File.Exists(file))
        {
    
    
            window.LoadFile(file);
        }
        
    }
    window.Show();
}
public void LoadFile(string path)
{
    
    
    this.Content = File.ReadAllText(path);
    this.Title = path;
}

启动程序,在窗体中显示文档的文本内容,在标题中显示文本的路径。
在这里插入图片描述
应用程序参数必须在startup事件属性中调用,相当于这个txt文档就是程序的一个配置参数。

访问当前Application对象

新建一个窗口Window1,并在APP.xaml文件中设置StartupUri="Window1.xaml"。这样运行文件会启动两个窗口。
Application.Current.MainWindow.Title可以知道当前应用程序的主窗体。

private void button_Click(object sender, RoutedEventArgs e)
{
    
    
    MessageBox.Show("当前的主窗体是:" + Application.Current.MainWindow.Title);
}

在这里插入图片描述
以下这种写法可以显示当前所有的窗体:

foreach (Window window in Application.Current.Windows)
{
    
    
    MessageBox.Show("当前的窗体有:" + window.Title);
}

在窗口之间进行交互

private void button1_Click(object sender, RoutedEventArgs e)
{
    
    
    foreach (Documents doc in ((App)Application.Current).Documents)
    {
    
    
        doc.Content = "Refreshed at" + DateTime.Now.ToLongTimeString()+".";
    }
}

点击第一个按钮,会新建一个document窗体,点击第二个按钮,会在窗体内容加上当前时间。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43511299/article/details/121606162