Close all open modal dialog windows
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 clos开发者_如何学运维e any MessageBox.Show instances. Is this possible?
Thanks, Matt
Have you tried to iterate the Application.Current.Windows collection, and close all these that are not the Application.Current.MainWindow?
Jogy
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).
精彩评论