- using System;
- using System.Text;
- using System.Runtime.InteropServices;
- public class OpenFolderDialog
- {
- /*
- private struct SHITEMID
- {
- ushort cb;
- byte adID; // BYTE abID[1];
- }
- private struct ITEMIDLIST
- {
- SHITEMID mkid;
- }
- */
- [StructLayout(LayoutKind.Sequential)]
- private struct BROWSEINFO
- {
- public IntPtr hwndOwner; // HWND hwndOwner
- public IntPtr pidlRoot; // const ITEMIDLIST* pidlRoot
- [MarshalAs(UnmanagedType.LPTStr)]
- public string pszDisplayName;
- [MarshalAs(UnmanagedType.LPTStr)]
- public string lpszTitle;
- public int ulFlags;
- [MarshalAs(UnmanagedType.FunctionPtr)]
- public BrowseCallBackProc lpfn;
- [MarshalAs(UnmanagedType.LPTStr)]
- public string lParam;
- public int iImage;
- }
- [DllImport("User32.Dll")]
- [return: MarshalAs(UnmanagedType.Bool)]
- private extern static bool SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPTStr)] string lParam);
- [DllImport("Shell32.dll", CharSet = CharSet.Auto)]
- private extern static IntPtr SHBrowseForFolder(ref BROWSEINFO lpbi);
- [DllImport("Shell32.dll", CharSet = CharSet.Auto)]
- [return: MarshalAs(UnmanagedType.Bool)]
- private extern static bool SHGetPathFromIDList(IntPtr pidl, StringBuilder pszPath);
- private delegate int BrowseCallBackProc(IntPtr hwnd, uint msg, IntPtr lParam, [MarshalAs(UnmanagedType.LPTStr)] string lpData);
- private static int BrowseCtrlCallback(IntPtr hwnd, uint uMsg, IntPtr lParam, [MarshalAs(UnmanagedType.LPTStr)] string lpData)
- {
- if (uMsg == 1) // BFFM_INITIALIZED
- {
- string szPath = lpData;
- if (szPath != null && szPath != "")
- {
- if (szPath[szPath.Length - 1] != '//')
- szPath += '//';
- SendMessage(hwnd, 0x400 + 103, 1, szPath); // BFFM_SETSELECTION
- }
- }
- return 0;
- }
- // hwndOwner:父窗体句柄
- // Title:标题;可以为null,也可以为""
- // lpszInitPath:初始目录;可以为null,也可以为"";为null或""时指向“我的电脑”
- // return:如果按下了“确定”按钮则为用户选择的目录,否则返回null
- public static string ShowDialog(IntPtr hwndOwner, string Title, string lpszInitPath)
- {
- BROWSEINFO BrInfo;
- BrInfo.hwndOwner = hwndOwner;
- BrInfo.pidlRoot = IntPtr.Zero;
- BrInfo.pszDisplayName = null;
- BrInfo.lpszTitle = Title;
- BrInfo.ulFlags = 0x0001; // BIF_RETURNONLYFSDIRS
- BrInfo.lpfn = new BrowseCallBackProc(BrowseCtrlCallback);
- BrInfo.lParam = lpszInitPath;
- BrInfo.iImage = 0;
- IntPtr pidlDestination = SHBrowseForFolder(ref BrInfo);
- string folderName = null;
- if (pidlDestination != IntPtr.Zero)
- {
- StringBuilder tmp = new StringBuilder(260); // MAX_PATH
- SHGetPathFromIDList(pidlDestination, tmp);
- folderName = tmp.ToString();
- }
- return folderName;
- }
- }
- ///调用方法
- this.strItemFolder = OpenFolderDialog.ShowDialog(this.Handle, "选择目录", @"C:/");
- if (strItemFolder != null)
- {
- ///set select save path.
- textBox_Path.Text = this.strItemFolder;
- ///获得目录 AND 创建目录
- }
- else
- {
- MessageBox.Show("靠,你按了“取消”按钮,啥也没选");
- }