日期:2013-04-29  浏览次数:20409 次

基本思路是利用SHBrowseForFolder 于是有如下代码:

private enum BrowseFlag
{
BIF_RETURNONLYFSDIRS = 0x0001, // For finding a folder to start document searching
BIF_DONTGOBELOWDOMAIN = 0x0002, // For starting the Find Computer
BIF_STATUSTEXT = 0x0004,
BIF_RETURNFSANCESTORS = 0x0008,
BIF_EDITBOX = 0x0010,
BIF_VALIDATE = 0x0020, // insist on valid result (or CANCEL)

BIF_BROWSEFORCOMPUTER = 0x1000, // Browsing for Computers.
BIF_BROWSEFORPRINTER = 0x2000, // Browsing for Printers
BIF_BROWSEINCLUDEFILES= 0x4000 // Browsing for Everything
}

[StructLayout(LayoutKind.Sequential)]
private struct BrowseInfo
{
public IntPtr hwndOwner;
public IntPtr pidlRoot;
[MarshalAs(UnmanagedType.LPTStr)]
public string displayname;
[MarshalAs(UnmanagedType.LPTStr)]
public string title;
public int flags;
public IntPtr callback;
public IntPtr lparam;
}

[DllImport("shell32.dll", CharSet=CharSet.Auto)]
static extern IntPtr SHBrowseForFolder(ref BrowseInfo info);
[DllImport("shell32.dll", CharSet=CharSet.Auto)]
[return : MarshalAs(UnmanagedType.Bool)]
internal extern static bool SHGetPathFromIDList(IntPtr pidl, [MarshalAs(UnmanagedType.LPTStr)] System.Text.StringBuilder pszPath);

public static string BrowseFolder(IWin32Window owner)
{
BrowseInfo info = new BrowseInfo();
info.flags = (int)BrowseFlag.BIF_RETURNONLYFSDIRS
+ (int)BrowseFlag.BIF_STATUSTEXT
+ (int)BrowseFlag.BIF_VALIDATE;
info.hwndOwner = owner.Handle;
IntPtr pidlReturned = SHBrowseForFolder(ref info);

StringBuilder sb = new StringBuilder(260);
SHGetPathFromIDList(pidlReturned, sb);

return sb.ToString();
}


这绝对是最简便的解决办法。虽然没有释放pidlReturned有可能造成少量内存泄漏,但是那么一点内存,谁在乎呢?