.NET and Windows Forms includes “FolderBrowserDialog” this is the common Directory browser dialog we’ve come to expect.
However the implementation leaves out a lot of the features of the underlying API. it doesn’t handle events, doesn’t support the new UI style, doesn’t allow for a edit box or status bar, etc. This is rather disappointing since my own VB6 implementation managed to do all these things. Since I’ve got a few programs that make use of the dialog and found myself- as a user of those applications- annoyed at the usability drop with the dialog, I set about creating an expanded version.
My original attempts went sour quite quickly… But I managed to sort the issue out in the last week or so.
SHBrowseForFolder
The underlying API of the FolderBrowserDialog is the SHBrowseForFolder API Function. This function is similar in design to other functions such as the GetOpenFilename and GetSaveFilename functions used by the OpenFileDialog and SaveFileDialog respectively (which both appear to lack support for their various notifications and messages…). You create a Structure and populate it, then send it to the function, then use the structure to get the result of the function call.
That is sufficient for basic usage of the function. However if you want to use advanced features- in particular, if you want any capabilities provided by using the callback, things get trickier. As I mentioned above, I found my original attempts to use the callback were hit or miss- with misses being more common. Typically, the problem manifested as a InvalidOperationException occurring in an unknown module, which made it difficult to really track down the issue. I was able to identify the issue as occurring within the callback function itself when the callback attempted to convert the IDList to a string path to fire an event. After fiddling with it for a while I managed to find some C/C++ examples of use of the bare API. They seemed to include uses of interfaces such as IMalloc that I hadn’t used, so I scrapped what I had and instead tried to port those implementations to C#. The result was a usable class that provides the full capabilities (I think) of the SHBrowseForFolder API Function, ready for me to insert as nearly a drop-in replacement for the BrowseFolderDialog.
I could explore this domain piecemeal- provide a basic working component, then draw it out with blog entries for each additional feature. Arguably, not a bad idea, but I cannot be trusted doing that, and realistically the version that would best benefit people would be the complete version- so here it is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
using System.ComponentModel; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace System.Windows.Shell { /// <summary> /// Flags for the SHBrowseFolder function call. /// </summary> [Flags] public enum BrowseFlags { /// <summary> /// BIF_RETURNONLYFSDIRS /// </summary> ReturnOnlyFSDirs = 0x0001, /// <summary> /// BIF_DONTGOBELOWDOMAIN /// </summary> DontGoBelowDomain = 0x0002, /// <summary> /// BIF_STATUSTEXT /// </summary> ShowStatusText = 0x0004, /// <summary> /// BIF_RETURNFSANCESTORS /// </summary> ReturnFSancestors = 0x0008, /// <summary> /// BIF_EDITBOX /// </summary> EditBox = 0x0010, /// <summary> /// BIF_VALIDATE /// </summary> Validate = 0x0020, /// <summary> /// BIF_NEWDIALOGSTYLE /// </summary> NewDialogStyle = 0x0040, /// <summary> /// BIF_BROWSEINCLUDEURLS /// </summary> BrowseIncludeURLs = 0x0080, /// <summary> /// BIF_UAHINT /// </summary> AddUsageHint = 0x0100, /// <summary> /// BIF_NONEWFOLDERBUTTON /// </summary> NoNewFolderButton = 0x0200, /// <summary> /// BIF_BROWSEFORCOMPUTER /// </summary> BrowseForComputer = 0x1000, /// <summary> /// BIF_BROWSEFORPRINTER /// </summary> BrowseForPrinter = 0x2000, /// <summary> /// BIF_BROWSEINCLUDEFILES /// </summary> IncludeFiles = 0x4000, /// <summary> /// BIF_SHAREABLE /// </summary> ShowShareable = 0x8000 } /// <summary> /// Event information when the item selection changes. /// </summary> public class BrowseSelChangedEventArgs : EventArgs, IDisposable { internal BrowseSelChangedEventArgs(IntPtr selectedItemPidl) { SelectedItemPidl = selectedItemPidl; } /// <summary> /// Return ITEMIDLIST for the currently selected folder /// </summary> public IntPtr SelectedItemPidl { get; private set; } /// <summary> /// uses the PIDL and retrieves the string representation for the given path. /// </summary> public string SelectedPath { get { var path = new StringBuilder(260); NativeMethods.SHGetPathFromIDList(SelectedItemPidl, path); return path.ToString(); } } public void Dispose() { NativeMethods.SHMemFree(SelectedItemPidl); } }; /// <summary> /// represents the IUnknown Message event. /// </summary> public class IUnknownObtainedEventArgs : EventArgs { internal IUnknownObtainedEventArgs(object siteUnknown) { SiteUnknown = siteUnknown; } public object SiteUnknown { get; private set; } } public class ValidationFailedEventArgs : EventArgs { internal ValidationFailedEventArgs(string invalidText) { Dismiss = false; InvalidText = invalidText; } /// <summary> /// The text which called validation to fail /// </summary> public string InvalidText { get; private set; } /// <summary> /// Sets whether the dialog needs to be dismissed or not /// </summary> public bool Dismiss { get; set; } } /// <summary> /// Encapsulates the shell folder browse dialog shown by SHBrowseForFolder /// </summary> public class BrowseFolderDialogEx : Component { private const int WM_USER = 0x0400; private const int BFFM_SETSTATUSTEXTA = (WM_USER + 100); private const int BFFM_SETSTATUSTEXTW = (WM_USER + 104); private const int BFFM_ENABLEOK = (WM_USER + 101); private const int BFFM_SETSELECTIONA = (WM_USER + 102); private const int BFFM_SETSELECTIONW = (WM_USER + 103); private const int BFFM_SETOKTEXT = (WM_USER + 105); private const int BFFM_SETEXPANDED = (WM_USER + 106); private const int BFFM_INITIALIZED = 1; private const int BFFM_SELCHANGED = 2; private const int BFFM_VALIDATEFAILEDA = 3; private const int BFFM_VALIDATEFAILEDW = 4; private const int BFFM_IUNKNOWN = 5; private IntPtr handle; private IntPtr pidlReturned = IntPtr.Zero; private string title; /// <summary> /// String displayed above the Dialog's treeview, intended for instructions. Can only be modified before displaying the /// dialog. /// </summary> [Description("String displayed above the Dialog's treeview, intended for instructions. Can only be modified before displaying the dialog.")] public string Title { get { return title; } set { if (handle != IntPtr.Zero) throw new InvalidOperationException(); title = value; } } /// <summary> /// retrieve display name of selected folder. /// </summary> [Description("The display name of the folder selected by the user")] public string FolderDisplayName { get; private set; } /// <summary> /// retrieves The folder path that was selected /// </summary> public string FolderPath { get { if (pidlReturned == IntPtr.Zero) return string.Empty; var pathReturned = new StringBuilder(260); NativeMethods.SHGetPathFromIDList(pidlReturned, pathReturned); return pathReturned.ToString(); } } /// <summary> /// Gets/Sets BIF behaviour flags. /// </summary> public BrowseFlags BrowseFlags { get; set; } private DialogResult ShowDialogInternal(ref BrowseInfo bi) { bi.title = title; bi.displayname = new string('\0', 260); bi.callback = BrowseCallback; bi.flags = (int)BrowseFlags; //Free any old pidls if (pidlReturned != IntPtr.Zero) NativeMethods.SHMemFree(pidlReturned); var ret = (pidlReturned = NativeMethods.SHBrowseForFolder(ref bi)) != IntPtr.Zero; if (ret) { FolderDisplayName = bi.displayname; } //Reset the handle handle = IntPtr.Zero; return ret ? DialogResult.OK : DialogResult.Cancel; } public static String DoBrowse(String pTitle, BrowseFlags pFlags, Action<Object, EventArgs> pInitialize = null, Action<Object, BrowseSelChangedEventArgs> pSelChanged = null, Action<Object, ValidationFailedEventArgs> pValidationFailure = null) { return DoBrowse(null, pTitle, pFlags, pInitialize, pSelChanged, pValidationFailure); } public static String DoBrowse(IWin32Window pOwner, String pTitle, BrowseFlags pFlags, Action<Object, EventArgs> pInitialize = null, Action<Object, BrowseSelChangedEventArgs> pSelChanged = null, Action<Object, ValidationFailedEventArgs> pValidationFailure = null) { BrowseFolderDialogEx bfd = new BrowseFolderDialogEx(); bfd.Title = pTitle; bfd.BrowseFlags = pFlags; if (pInitialize != null) bfd.Initialized += (EventHandler)((ob, e) => { pInitialize(ob, e); }); if (pSelChanged != null) bfd.SelChanged += (EventHandler<BrowseSelChangedEventArgs>)((ob, e) => { pSelChanged(ob, e); }); if (pValidationFailure != null) bfd.ValidateFailed += (EventHandler<ValidationFailedEventArgs>)((ob, e) => { pValidationFailure(ob, e); }); DialogResult result; if (pOwner != null) result = bfd.ShowDialog(pOwner); else result = bfd.ShowDialog(); if (result == DialogResult.OK) return bfd.FolderPath; else return null; } /// <summary> /// Shows the dialog /// </summary> /// <param name="owner">The window to use as the owner</param> /// <returns></returns> public DialogResult ShowDialog(IWin32Window owner) { if (handle != IntPtr.Zero) throw new InvalidOperationException(); var bi = new BrowseInfo(); if (owner != null) bi.hwndOwner = owner.Handle; return ShowDialogInternal(ref bi); } /// <summary> /// Shows the dialog using active window as the owner /// </summary> public DialogResult ShowDialog() { return ShowDialog(Form.ActiveForm); } /// <summary> /// Sets the text of the status area of the folder dialog /// </summary> /// <param name="text">Text to set</param> public void SetStatusText(string text) { if (handle == IntPtr.Zero) throw new InvalidOperationException(); var msg = (Environment.OSVersion.Platform == PlatformID.Win32NT) ? BFFM_SETSTATUSTEXTW : BFFM_SETSTATUSTEXTA; var strptr = Marshal.StringToHGlobalAuto(text); NativeMethods.SendMessage(handle, msg, IntPtr.Zero, strptr); Marshal.FreeHGlobal(strptr); } /// <summary> /// Enables or disables the ok button /// </summary> /// <param name="bEnable">true to enable false to diasble the OK button</param> public void EnableOkButton(bool bEnable) { if (handle == IntPtr.Zero) throw new InvalidOperationException(); var lp = bEnable ? new IntPtr(1) : IntPtr.Zero; NativeMethods.SendMessage(handle, BFFM_ENABLEOK, IntPtr.Zero, lp); } /// <summary> /// Sets the selection the text specified /// </summary> /// <param name="newsel">The path of the folder which is to be selected</param> public void SetSelection(string newsel) { if (handle == IntPtr.Zero) throw new InvalidOperationException(); var msg = (Environment.OSVersion.Platform == PlatformID.Win32NT) ? BFFM_SETSELECTIONA : BFFM_SETSELECTIONW; var strptr = Marshal.StringToHGlobalAuto(newsel); NativeMethods.SendMessage(handle, msg, new IntPtr(1), strptr); Marshal.FreeHGlobal(strptr); } /// <summary> /// Sets the text of the OK button in the dialog /// </summary> /// <param name="text">New text of the OK button</param> public void SetOkButtonText(string text) { if (handle == IntPtr.Zero) throw new InvalidOperationException(); var strptr = Marshal.StringToHGlobalUni(text); NativeMethods.SendMessage(handle, BFFM_SETOKTEXT, new IntPtr(1), strptr); Marshal.FreeHGlobal(strptr); } /// <summary> /// Expand a path in the folder /// </summary> /// <param name="path">The path to expand</param> public void SetExpanded(string path) { var strptr = Marshal.StringToHGlobalUni(path); NativeMethods.SendMessage(handle, BFFM_SETEXPANDED, new IntPtr(1), strptr); Marshal.FreeHGlobal(strptr); } /// <summary> /// Fired when the dialog is initialized /// </summary> public event EventHandler Initialized; /// <summary> /// Fired when selection changes /// </summary> public event EventHandler<BrowseSelChangedEventArgs> SelChanged; /// <summary> /// Shell provides an IUnknown through this event. (For details see documentation of SHBrowseForFolder) /// </summary> public event EventHandler<IUnknownObtainedEventArgs> IUnknownObtained; /// <summary> /// Fired when validation of text typed by user into the edit box fails. /// </summary> public event EventHandler<ValidationFailedEventArgs> ValidateFailed; private void FireInitialized(object sender, EventArgs e) { var copied = Initialized; if (copied != null) copied(sender, e); } private void FireSelChanged(Object sender, BrowseSelChangedEventArgs e) { var copied = SelChanged; if (copied != null) copied(sender, e); } private void FireIUnknownObtained(Object sender, IUnknownObtainedEventArgs e) { var copied = IUnknownObtained; if (copied != null) copied(sender, e); } private void FireValidateFailed(Object sender, ValidationFailedEventArgs e) { var copied = ValidateFailed; if (copied != null) copied(sender, e); } private int BrowseCallback(IntPtr hwnd, int msg, IntPtr lp, IntPtr lpData) { var ret = 0; switch (msg) { case BFFM_INITIALIZED: handle = hwnd; FireInitialized(this, null); break; case BFFM_IUNKNOWN: if (IUnknownObtained != null) { if (lp != IntPtr.Zero) { var obtained = Marshal.GetObjectForIUnknown(lp); if (obtained != null) FireIUnknownObtained(this, new IUnknownObtainedEventArgs(obtained)); } } break; case BFFM_SELCHANGED: if (SelChanged != null) { var e = new BrowseSelChangedEventArgs(lp); FireSelChanged(this, e); } break; case BFFM_VALIDATEFAILEDA: if (ValidateFailed != null) { var e = new ValidationFailedEventArgs(Marshal.PtrToStringAnsi(lpData)); FireValidateFailed(this, e); ret = (e.Dismiss) ? 0 : 1; } break; case BFFM_VALIDATEFAILEDW: if (ValidateFailed != null) { var e = new ValidationFailedEventArgs(Marshal.PtrToStringUni(lpData)); FireValidateFailed(this, e); ret = (e.Dismiss) ? 0 : 1; } break; } return ret; } protected override void Dispose(bool disposing) { if (pidlReturned != IntPtr.Zero) { NativeMethods.SHMemFree(pidlReturned); pidlReturned = IntPtr.Zero; } } } internal delegate int BrowseCallBackProc(IntPtr hwnd, int msg, IntPtr lp, IntPtr wp); [StructLayout(LayoutKind.Sequential)] internal struct BrowseInfo { public IntPtr hwndOwner; public IntPtr pidlRoot; [MarshalAs(UnmanagedType.LPTStr)] public string displayname; [MarshalAs(UnmanagedType.LPTStr)] public string title; public int flags; [MarshalAs(UnmanagedType.FunctionPtr)] public BrowseCallBackProc callback; public IntPtr lparam; } [ComImport] [Guid("00000002-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IMalloc { [PreserveSig] IntPtr Alloc(IntPtr cb); [PreserveSig] IntPtr Realloc(IntPtr pv, IntPtr cb); [PreserveSig] void Free(IntPtr pv); [PreserveSig] IntPtr GetSize(IntPtr pv); [PreserveSig] int DidAlloc(IntPtr pv); [PreserveSig] void HeapMinimize(); } /// <summary> /// A class that defines all the native/unmanaged methods used /// </summary> internal class NativeMethods { [DllImport("Shell32.dll", CharSet = CharSet.Auto)] internal static extern IntPtr SHBrowseForFolder(ref BrowseInfo bi); [DllImport("Shell32.dll", CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SHGetPathFromIDList(IntPtr pidl, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder pszPath); [DllImport("User32.Dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SendMessage(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp); [DllImport("Shell32.dll")] internal static extern int SHGetMalloc([MarshalAs(UnmanagedType.IUnknown)] out object shmalloc); //Helper routine internal static void SHMemFree(IntPtr ptr) { object shmalloc = null; if (SHGetMalloc(out shmalloc) == 0) { var malloc = (IMalloc)shmalloc; (malloc).Free(ptr); } } } } |
And of course any code sample like this is not complete without at least a basic usage example. the class contains a static method that can be called directly for more straightforward usage, or the standard pattern of creating the class, setting properties, and using ShowDialog() can also be used:
1 2 |
String strResult = BrowseFolderDialogEx.DoBrowse(this, "Testing!",BrowseFlags.ReturnOnlyFSDirs|BrowseFlags.EditBox); MessageBox.Show(strResult); |
I’m considering further additions such as trying to implement checkboxes, though I’m not sure how safe such a feature could be since it would require directly manipulating the treeview control and giving it the checkboxes style.
Have something to say about this post? Comment!