Close all open modal dialog windows

怎甘沉沦 提交于 2019-12-10 20:58:26

问题


I have a WPF application that has several modal window used for various purposes. This is easily accomplished by using the ShowDialog function. However, in my application I have a timer to measure idle time (i.e. no mouse moves or key strokes) that will cause the user to be logged off. Is there a way (when this timer fires) to find and close all open modal windows without tracking each explicitly?

Update I would also like to close any MessageBox.Show instances. Is this possible?

Thanks, Matt


回答1:


Is there a way (when this timer fires) to find and close all open modal windows without tracking each explicitly?

You could use ComponentDispatcher.IsThreadModal to check to see if you're UI thread is in a modal state. If it is, the Application.Current.Windows property will give you the list of opened Windows.

If you only have a single MainWindow, you could close any others (as they'd be your modal dialogs), but if you have multiple windows, you'd have to check each one.

Unfortunately, there's no direct API to determine whether a specific Window is modal - but there is a private variable in the Window class you could use to do this. For example, the following method uses reflection to determine whether a Window is modal:

  public static bool IsModal(Window window)
  {
       Type type = typeof(Window);
       var field = type.GetField("_showingAsDialog", BindingFlags.Instance | BindingFlags.NonPublic);
       return field.GetValue(window);
  }

This is, unfortunately, subject to change (since it's using undocumented private members).




回答2:


Have you tried to iterate the Application.Current.Windows collection, and close all these that are not the Application.Current.MainWindow?

Jogy



来源:https://stackoverflow.com/questions/5093899/close-all-open-modal-dialog-windows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!