首页 > 开发 > 综合 > 正文

[C#] 如何选择一个目录

2024-07-21 02:18:21
字体:
来源:转载
供稿:网友
基本思路是利用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有可能造成少量内存泄漏,但是那么一点内存,谁在乎呢?


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表