wpffolderbrowserdialog

Is Owner Window required in WPF FolderBrowserDialog in 2021?


When using FolderBrowserDialog in WPF, I've seen a few answers where using the Win32 API is required to make it modal. For example,

Using FolderBrowserDialog in WPF application

How to use a FolderBrowserDialog from a WPF application

Actually, is the Win32 Api REALLY required ? I just tried the FolderBrowserDialog and it is already modal by default; simply calling .ShowDialog() is already modal to the underlying window. (What are the other answers talking about or have the wpf internals changed ?)

EDIT: using Visual Studio 2015 with .NET framework (not core)


Solution

  • Actually, is the Win32 Api REALLY required

    Yes. The FolderBrowserDialog is exposed through Win32. You can't write software for Windows without using Win32 in some way or another.

    I just tried the FolderBrowserDialog and it is already modal by default; simply calling .ShowDialog() is already modal to the underlying window.

    That's because when you call ShowDialog() it passes IntPtr.Zero for the owner hWnd parameter (the same as NULL in C). When you pass NULL then Windows uses the currently active window in the process as the owner - so an owner is still set, it's just determined automatically:

    From the documentation for WinForms' ShowDialog() (the overload without the owner parameter. While WinForms and WPF are separate, the principle is the same for both):

    When this version is called, the currently active window is made the owner of the dialog box. If you want to specify a specific owner, use the other version of this method.

    That said, you should still specify the owner hWnd where possible because you may rearchitect your application and may want a different window to be the owner (e.g. when you want to show a dialog immediately after the non-root parent window closes)