/// <summary> /// Shows the folder browser dialog box with the specified owner window. /// </summary> protected override bool RunDialog(IntPtr hWndOwner) { IntPtr pidlRoot = IntPtr.Zero; bool flag = false; // Get the IDL for the specific startLocation. e.g. Environment.SpecialFolder.Desktop NativeWindowCommon.SHGetSpecialFolderLocation(hWndOwner, (int)this.rootFolder, ref pidlRoot); if (pidlRoot == IntPtr.Zero) { // Get the IDL for the default startLocation. NativeWindowCommon.SHGetSpecialFolderLocation(hWndOwner, 0, ref pidlRoot); if (pidlRoot == IntPtr.Zero) { throw new InvalidOperationException(); } } int flags = GetFlags(); if ((flags & (int)NativeWindowCommon.BffStyles.NewDialogStyle) != 0) { if (System.Threading.ApartmentState.MTA == Application.OleRequired()) { flags = flags & (~(int)NativeWindowCommon.BffStyles.NewDialogStyle); } } IntPtr pidl = IntPtr.Zero; IntPtr hglobal = IntPtr.Zero; try { hglobal = Marshal.AllocHGlobal((int)(MAX_PATH * Marshal.SystemDefaultCharSize)); this.callback = new NativeWindowCommon.BrowseCallbackProc(this.FolderBrowserDialog_BrowseCallbackProc); NativeWindowCommon.BROWSEINFO lpbi = new NativeWindowCommon.BROWSEINFO { pidlRoot = pidlRoot, hwndOwner = hWndOwner, pszDisplayName = hglobal, lpszTitle = this.descriptionText, ulFlags = flags, lpfn = this.callback, lParam = IntPtr.Zero, iImage = 0 }; // Show the dialog. pidl = NativeWindowCommon.SHBrowseForFolder(ref lpbi); if (pidl != IntPtr.Zero) { // Retrieve the path from the IDList. StringBuilder sb = new StringBuilder(MAX_PATH * Marshal.SystemDefaultCharSize); NativeWindowCommon.SHGetPathFromIDList(pidl, sb); this.selectedPathNeedsCheck = true; this.selectedPath = sb.ToString(); flag = true; } } finally { NativeWindowCommon.IMalloc malloc = GetSHMalloc(); //Free the memory allocated for getting the ID list for the specific startLocation. malloc.Free(pidlRoot); if (pidl != IntPtr.Zero) { //Free the memory allocated for getting the ID list for the showing the SHBrowseForFolder. malloc.Free(pidl); } // Free the buffer you've allocated on the global heap. if (hglobal != IntPtr.Zero) { Marshal.FreeHGlobal(hglobal); } //Reset the callback function to null. this.callback = null; } return(flag); }