在模式对话框打开时如何处理锁定应用程序?

时间:2019-06-13 14:32:43

标签: c# .net wpf

我正在处理的应用程序使用模式对话框。我目前正在实现会话超时,该超时将在一定时间的不活动分钟后自动锁定屏幕,但是遇到一个问题,如果用户打开了模式对话框,它将显示在会话锁定屏幕的顶部。

在WPF .Net应用程序中用于标识和强制关闭任何模式对话框(使用“取消”动作)的一般逻辑是什么?

1 个答案:

答案 0 :(得分:1)

模态对话框有些复杂,最好通过示例来说明。以下处理程序会在点击时产生一个新的func (s Srv) init() { s.A = make([][]int, 0) } ,然后是Window,等待一秒钟,然后关闭两者。请注意,我们希望MessageBox保持打开状态。

MainWindow

此示例的主要优点是非模式窗口和MessageBox均已关闭。但是,如果我们仔细观察public partial class MainWindow : Window { const int timeout = 1000; public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { var win = new Window { Content = new Label { Content = "Not a modal Window" } }; using (new Timer(OnTimerElapsed, win, timeout, Timeout.Infinite)) { win.Show(); MessageBox.Show($"Open windows: {Application.Current.Windows.Count}", "Just a sec..."); } } private void OnTimerElapsed(object state) { Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Background, new Action(() => { ((Window)state).Close(); })); } } ,就会发现只有非模态窗口被告知关闭。假设该窗口是OnTimerElapsed被调用时(最后一个)活动窗口,它也是MessageBox的所有者,因此关闭它也会关闭MessageBox。

我们可以将MessageBox.Show行替换为MessageBox.Show(...);,并获得相似的结果。

这使我们达到了最高水平。如果我们要关闭从主窗口实例化的MessageBox怎么办,如何在不同时关闭两者的情况下实现呢?一种选择是创建一个虚拟所有者窗口,该窗口永远不会显示,而只是充当调用new OpenFileDialog().ShowDialog();的引用。

Close

在这里,我们迭代当前public partial class MainWindow : Window { const int timeout = 1000; private Window _modalOwner; public MainWindow() { InitializeComponent(); InitializeModalOwner(); } private void InitializeModalOwner() { _modalOwner = new Window { AllowsTransparency = true, ShowInTaskbar = false, WindowStyle = WindowStyle.None, Background = Brushes.Transparent }; _modalOwner.Show(); } private void Button_Click(object sender, RoutedEventArgs e) { using (new Timer(OnTimerElapsed, null, timeout, Timeout.Infinite)) { MessageBox.Show(_modalOwner, $"Open windows: {Application.Current.Windows.Count}", "Just a sec..."); } } private void OnTimerElapsed(object state) { Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Background, new Action(() => { var mainWindow = Application.Current.MainWindow; foreach (Window win in Application.Current.Windows) if(win != mainWindow) win.Close(); InitializeModalOwner(); })); } } 中的所有窗口,并关闭它们,只要它们不是我们应用程序的主窗口即可。之后,WindowCollection也将被关闭,从而使其无用-一旦关闭,您将无法在_modalOwner实例上调用Show。因此,这也是再次对其进行初始化的地方。

Window也是如此。您调用new OpenFileDialog().ShowDialog(_modalOwner);的所有Window实例将自动添加到ShowDialog集合中。

资源资源