private int _browseCallbackHandler(IntPtr hDlg, int msg, IntPtr lParam, IntPtr lpData) { switch (msg) { case Win32.BFFM_INITIALIZED: // remove context help button from dialog caption int lStyle = Win32.GetWindowLong(hDlg, Win32.GWL_STYLE); lStyle &= ~Win32.DS_CONTEXTHELP; Win32.SetWindowLong(hDlg, Win32.GWL_STYLE, lStyle); lStyle = Win32.GetWindowLong(hDlg, Win32.GWL_EXSTYLE); lStyle &= ~Win32.WS_EX_CONTEXTHELP; Win32.SetWindowLong(hDlg, Win32.GWL_EXSTYLE, lStyle); _adjustUi(hDlg, lpData); break; case Win32.BFFM_SELCHANGED: { bool ok = false; StringBuilder sb = new StringBuilder(Win32.MAX_PATH); if (Win32.SHGetPathFromIDList(lParam, sb)) { ok = true; string dir = sb.ToString(); IntPtr hEdit = Win32.GetDlgItem(hDlg, CtlIds.PATH_EDIT); Win32.SetWindowText(hEdit, dir); #if UsingStatusText // We're not using status text, but if we were, this is how you'd set it Win32.SendMessage(hDlg, Win32.BFFM_SETSTATUSTEXTW, 0, dir); #endif #if SHBrowseForFolder_lists_links // This check doesn't seem to be necessary - the SHBrowseForFolder dirtree doesn't seem to list links Win32.SHFILEINFO sfi = new Win32.SHFILEINFO(); Win32.SHGetFileInfo(lParam, 0, ref sfi, Marshal.SizeOf(sfi), Win32.SHGFI_PIDL | Win32.SHGFI_ATTRIBUTES); // fail if pidl is a link if ((sfi.dwAttributes & Win32.SFGAO_LINK) == Win32.SFGAO_LINK) { ok = false; } #endif } // if invalid selection, disable the OK button if (!ok) { Win32.EnableWindow(Win32.GetDlgItem(hDlg, CtlIds.IDOK), false); } break; } } return(0); }
public DialogResult ShowDialog(IWin32Window owner) { InitData initdata = new InitData(this, owner.Handle); Win32.BROWSEINFO bi = new Win32.BROWSEINFO { iImage = 0, hwndOwner = owner.Handle }; if (Win32.SHGetSpecialFolderLocation(owner.Handle, (int)RootFolder, ref bi.pidlRoot) != 0) { bi.pidlRoot = IntPtr.Zero; } bi.lpszTitle = ""; bi.ulFlags = Win32.BIF_RETURNONLYFSDIRS; // do NOT use BIF_NEWDIALOGSTYLE or BIF_STATUSTEXT if (ShowEditbox) { bi.ulFlags |= Win32.BIF_EDITBOX; } if (!ShowNewFolderButton) { bi.ulFlags |= Win32.BIF_NONEWFOLDERBUTTON; } bi.lpfn = _browseCallbackHandler; // Initialization data, used in _browseCallbackHandler IntPtr hInit = Marshal.AllocHGlobal(Marshal.SizeOf(initdata)); Marshal.StructureToPtr(initdata, hInit, true); bi.lParam = hInit; IntPtr pidlSelectedPath = IntPtr.Zero; try { pidlSelectedPath = Win32.SHBrowseForFolder(ref bi); StringBuilder sb = new StringBuilder(256); if (Win32.SHGetPathFromIDList(pidlSelectedPath, sb)) { SelectedPath = sb.ToString(); return(DialogResult.OK); } } finally { // Caller is responsible for freeing this memory. Marshal.FreeCoTaskMem(pidlSelectedPath); } return(DialogResult.Cancel); }