using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Blood.Com.ClassLib
{
///
/// 目录对话框控件
///
public class DirectoryDialog
{
[ StructLayout( LayoutKind.Sequential, CharSet=CharSet.Ansi )]
///
///浏览信息
///
public struct BROWSEINFO
{
public IntPtr hWndOwner;
public int pIDLRoot;
public string pszDisplayName;
public string lpszTitle;
public int ulFlags;
public int lpfnCallback;
public int lParam;
public int iImage;
}
private const int MAX_PATH = 260;
///
/// 指定浏览类型
///
public enum BrowseForTypes
{
///
/// 浏览计算机
///
Computers = 0x1000,
///
/// 浏览目录
///
Directories = 0x1,
///
/// 浏览目录和文件
///
///
FilesAndDirectories = 0x4000, // 4.71版
///
/// 浏览系统根目录
///
FileSystemAncestors = 0x8
}
[ DllImport( "ole32.dll")]
private static extern int CoTaskMemFree(IntPtr hMem);
[ DllImport( "kernel32.dll")]
private static extern IntPtr lstrcat(string lpString1, string lpString2);
[ DllImport( "shell32.dll")]
private static extern IntPtr SHBrowseForFolder(ref BROWSEINFO lpbi);
[ DllImport( "shell32.dll")]
private static extern int SHGetPathFromIDList(IntPtr pidList, StringBuilder lpBuffer);
///
/// 显示公共文件夹对话框
///
/// 文件夹对话框所有者
protected bool RunDialog(IntPtr hWndOwner)
{
BROWSEINFO udtBI = new BROWSEINFO();
IntPtr lpIDList;
GCHandle hTitle = GCHandle.Alloc(Title, GCHandleType.Pinned);
// 设置WINDOWS的所有者
udtBI.hWndOwner = hWndOwner;
// 设置WINDOWS的所有者
udtBI.lpszTitle = Title;
// 设置WINDOWS的所有者
udtBI.ulFlags = (int)BrowseFor;
// 创建一个字符串缓冲用来显示名称
StringBuilder buffer = new StringBuilder(MAX_PATH);
buffer.Length = MAX_PATH;
udtBI.pszDisplayName = buffer.ToString();
// 显示浏览目录对话框
lpIDList = SHBrowseForFolder(ref udtBI);
hTitle.Free();
if (lpIDList.ToInt64() != 0)
{
if (BrowseFor == BrowseForTypes.Computers)
{
m_Selected = udtBI.pszDisplayName.Trim();
}
else
{
StringBuilder path = new StringBuilder(MAX_PATH);
//从lpIDList中取得路径
SHGetPathFromIDList(lpIDList, path);
m_Selected = path.ToString();
}
//释放内存
CoTaskMemFree(lpIDList);
}
else
{
return false;
}
return true;
}
///
public DialogResult ShowDialog()
{
return ShowDialog(null);
}
///
/// The owner of the folder dialog.
public DialogResult ShowDialog(IWin32Window owner)
{
IntPtr handle;
if (owner != null)
handle = owner.Handle;
else
handle = IntPtr.Zero;
if (RunDialog(handle))
{
return DialogResult.OK;
}
else
{
return DialogResult.Cancel;
}
}
///
/// 指定对话框的标题
///
///
///
public string Title
{
get
{
return m_Title;
}
set
{
if (value == null)
throw new ArgumentNullException();
m_Title = value;
}
}
///
///
public string Selected
{
get
{
return m_Selected;
}
}
///
///
public BrowseForTypes BrowseFor
{
get
{
return m_BrowseFor;
}
set
{
m_BrowseFor = value;
}
}
//申明私有变量
private BrowseForTypes m_BrowseFor = BrowseForTypes.Directories;
private string m_Title = "";
private string m_Selected = "";
///
/// 构造函数
///
public DirectoryDialog()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
}
}

