如何在WPF中关闭所有打开的表单 [英] How to close all open forms in WPF

查看:72
本文介绍了如何在WPF中关闭所有打开的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有两个按钮可以打开和关闭

当我单击打开"按钮时,窗口将打开,当我单击关闭"按钮时,窗口将关闭.

当我单击打开按钮3次时,3窗口将被打开.当我单击关闭按钮时,我想关闭所有窗口.

这是我的代码[请不要尝试更改线程,因为这是我的应用程序中的要求]

In my Application i have two button open and close

when i click open button window will be open, when i click close button window will be close.

when i click open button 3 time ,3 window will be opened . i want to close all window when i click close button.

here is my code [Please don''t try to Change the Thread because that is my requirement in my Application]

public partial class MainWindow : Window
{
    Window ProgressWindow;
    Thread ProgressThread;
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Open_Click(object sender, RoutedEventArgs e)
    {
        ProgressThread = new Thread(() =>
        {
            ProgressWindow = new Window();
            ProgressWindow.Margin = new Thickness(0, 0, 50, 0);
            ProgressWindow.WindowState = WindowState.Normal;
            ProgressWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            ProgressWindow.Height = 180;
            ProgressWindow.Width = 180;
            ProgressWindow.Content = "Hello WPF";
            ProgressWindow.ShowInTaskbar = false;
            ProgressWindow.Show();
            ProgressWindow.Closed += (sender2, e2) =>
            ProgressWindow.Dispatcher.InvokeShutdown();
            System.Windows.Threading.Dispatcher.Run();
        });
        ProgressThread.SetApartmentState(ApartmentState.STA);
        ProgressThread.Start();
    }

    private void Close_Click(object sender, RoutedEventArgs e)
    {
       
        if (ProgressThread.IsAlive == true)
        {
            ProgressThread.Abort();
        } 
       
    }
}

推荐答案

而不是在您的ProgressThread成员中持有一个Thread,而是将其中的一个IList插入,每次添加一个单击打开,并在关闭上对该列表中的所有线程调用Abort,然后清除该列表.

希望这会有所帮助,
弗雷德里克(Fredrik)
Instead of holding a single Thread in your ProgressThread member, hold a IList of them instread, add one every time Open is clicked, and call Abort on all threads in that list on Close and then clear the list.

Hope this helps,
Fredrik


这篇关于如何在WPF中关闭所有打开的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆