Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FolderBrowserDialog - Win32Exception occurred - The parameter is incorrect

Tags:

c#

wpf

I try to use the FolderBrowserDialog from WPF like this:

public static bool BrowseFolder(out string folderName)
{
   using (System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog())
   {
        var result = dlg.ShowDialog();
        folderName = dlg.SelectedPath;
        return result == System.Windows.Forms.DialogResult.OK;
   }
}

When using "break on exception" in Visual Studio 2010 I get an Exception after closing the Dialog in the ShowDialog() call. I'm curious why this occurs.

Exception: Win32Exception
Message: The parameter is incorrect
Stacktrace: at MS.Win32.UnsafeNativeMethods.SetFocus(HandleRef hWnd)

Update
I also tried to set the parent explicitly, but the exception was thrown nonetheless.

var w = new System.Windows.Interop.WindowInteropHelper(parent);
System.Windows.Forms.IWin32Window i = new WindowWrapper(w.Handle);
result = dlg.ShowDialog(i);
like image 445
testalino Avatar asked Aug 09 '10 10:08

testalino


1 Answers

This is just a bit of interop nastiness. The WPF code tries to set the focus back to the main window when the dialog is closing. Problem is, the dialog has disabled the window so it can't receive the focus yet. WPF is too eager to change the focus and doesn't otherwise know anything about the dialog behavior. Nothing actually goes wrong.

like image 73
Hans Passant Avatar answered Oct 24 '22 13:10

Hans Passant