/// <summary> /// Shows the dialog box to let the user browse for and select a folder. /// </summary> /// <param name="parentWindowHandle">The HWND of the parent window.</param> /// <returns>The selected folder or <c>null</c> if no folder was selected by the user.</returns> protected override bool RunDialog(IntPtr parentWindowHandle) { // Make sure OLE is initialized. This is a prerequisite for calling SHBrowseForFolder. NativeMethods.OleInitialize(IntPtr.Zero); IntPtr rpidl = IntPtr.Zero; NativeMethods.SHGetSpecialFolderLocation(parentWindowHandle, (int)RootFolder, out rpidl); if (rpidl == IntPtr.Zero) { NativeMethods.SHGetSpecialFolderLocation(parentWindowHandle, 0, out rpidl); if (rpidl == IntPtr.Zero) { throw new InvalidOperationException("No root folder specified for FolderBrowserDialog2."); } } if (Control.CheckForIllegalCrossThreadCalls && (Application.OleRequired() != System.Threading.ApartmentState.STA)) { throw new System.Threading.ThreadStateException("Debugging Exception Only. Thread must be STA."); } BrowseInfoFlag browseInfoFlag = BrowseInfoFlag.BIF_NEWDIALOGSTYLE | BrowseInfoFlag.BIF_SHAREABLE; if (!ShowNewFolderButton) { browseInfoFlag |= BrowseInfoFlag.BIF_NONEWFOLDERBUTTON; } if (ShowFolderPathEditBox) { browseInfoFlag |= BrowseInfoFlag.BIF_EDITBOX | BrowseInfoFlag.BIF_VALIDATE; } if (ShowFiles) { browseInfoFlag |= BrowseInfoFlag.BIF_BROWSEINCLUDEFILES; } browseInfoFlag |= (BrowseInfoFlag)BrowserFlag; NativeMethods.BROWSEINFO bi; bi.hwndOwner = parentWindowHandle; bi.pidlRoot = rpidl; bi.pszDisplayName = new string('\0', 260); bi.lpszTitle = Description; bi.ulFlags = (uint)browseInfoFlag; bi.lpfn = new NativeMethods.BrowseCallBackProc(OnBrowseEvent); bi.lParam = IntPtr.Zero; bi.iImage = 0; StringBuilder sb = new StringBuilder(260); IntPtr pidl = IntPtr.Zero; try { pidl = NativeMethods.SHBrowseForFolder(ref bi); if (((browseInfoFlag & BrowseInfoFlag.BIF_BROWSEFORPRINTER) == BrowseInfoFlag.BIF_BROWSEFORPRINTER) || ((browseInfoFlag & BrowseInfoFlag.BIF_BROWSEFORCOMPUTER) == BrowseInfoFlag.BIF_BROWSEFORCOMPUTER)) { SelectedPath = bi.pszDisplayName; } else { if (pidl == IntPtr.Zero || 0 == NativeMethods.SHGetPathFromIDList(pidl, sb)) { return(false); } SelectedPath = sb.ToString(); } return(true); } finally { if (rpidl != IntPtr.Zero) { Marshal.FreeCoTaskMem(rpidl); } if (pidl != IntPtr.Zero) { Marshal.FreeCoTaskMem(pidl); } } }