Click here to Skip to main content
15,886,080 members
Articles / Desktop Programming / WPF
Tip/Trick

WPF - Auto-Closing Modeless Windows

Rate me:
Please Sign up or sign in to vote.
4.54/5 (5 votes)
27 Feb 2021CPOL1 min read 6K   4   3
How to close modeless windows if you don't close them before the main window closes

Introduction

Modeless windows - they're pretty handy. The things they're handy for are way too numerous to iterate, so you'll just have to take my word for it. The problem with modeless windows is that unless you specifically close them before (or when) the main window closes, they'll stay open even after the main window is closed.

The Solution to the Modeless Problem

The fix is a simple matter of knowing when the main window (or the owning window) is closing. In order to do that, you simply handle the owner's Closing event. I wrote a method that takes care of this chore (you can certainly do it the way that makes sense to you):

C#
protected void HandleModeless()
{
    if (!this.IsModal())
    {
        // see if the owner was specified
        if (this.Owner == null)
        {
            // and if not, use the app's main window
            this.Owner = Application.Current.MainWindow;
        }
        // if we have an owner
        if (this.Owner != null)
        {
            // handle the close event so we can close the window when the 
            // owner closes
            Owner.Closing += this.Owner_Closing;
        }
    }
}

The event handler is very simple. It simply closes the form.

C#
protected virtual void Owner_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    this.Close();
}

You may have noticed the if condition at the top of the HandleModelss method.

C#
if (!this.IsModal())

In my case, this is an Window extension method that reads a private Window property that can be used to determine if the window is modal.

C#
public static class ExtendWpfWindow
{
    public static bool IsModal(this Window window)
    {
        // it should be safe to do this all in a single line of code because this is an 
        // extension method for the Window class
        return (bool)(typeof(Window).GetField("_showingAsDialog", 
               BindingFlags.Instance | BindingFlags.NonPublic).GetValue(window));
    }
}

You certainly don't have to use this extension method. In fact, you can do it right in the window's code:

C#
protected void HandleModeless()
{
    if (!(bool)(typeof(Window).GetField("_showingAsDialog", 
               BindingFlags.Instance | BindingFlags.NonPublic).GetValue(window)))
    {
        ...
    }
}

or even put a method in the window's code:

C#
private bool IsModal()
{
    return ((bool)(typeof(Window).GetField("_showingAsDialog", 
               BindingFlags.Instance | BindingFlags.NonPublic).GetValue(window)));
}

protected void HandleModeless()
{
    if (!this.IsModal())
    {
        ...
    }
}

I personally think it's more convenient if done with an extension method, especially if you have an assembly with commonly used code, and you don't want to have to remember exactly how to do something that an extension method does for you, not to mention an extension method is more readily re-usable.

It's my humble opinion that Microsoft should have handled this for us in the WPF framework, because this is the kind of stuff developers shouldn't have to concern themselves with except under special circumstances.

History

  • 2021.02.27 - Initial publication.
     

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

 
QuestionThanks and a question Pin
Amarnath S23-Oct-21 2:38
professionalAmarnath S23-Oct-21 2:38 
AnswerRe: Thanks and a question Pin
#realJSOP24-Oct-21 21:41
mve#realJSOP24-Oct-21 21:41 
GeneralRe: Thanks and a question Pin
Amarnath S25-Oct-21 5:21
professionalAmarnath S25-Oct-21 5:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.