C# WinForm 选择文件夹对话框
选择文件夹只有选择 FolderBrowserDialog,这种选择对话框让人有些抓狂,特别当文件目录比较深、需要多次选择文件夹操作时。
参考:自定义文件夹选择对话框 - 我也是个傻瓜 - 博客园 (cnblogs.com)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | using System; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Security; using System.Windows.Forms; public class SelectFolderDialog { #region Internal Enums internal enum FDAP { FDAP_BOTTOM = 0, FDAP_TOP = 1 } internal enum FDE_OVERWRITE_RESPONSE { FDEOR_DEFAULT = 0x00000000, FDEOR_ACCEPT = 0x00000001, FDEOR_REFUSE = 0x00000002 } internal enum FDE_SHAREVIOLATION_RESPONSE { FDESVR_DEFAULT = 0x00000000, FDESVR_ACCEPT = 0x00000001, FDESVR_REFUSE = 0x00000002 } [Flags] internal enum FOS : uint { FOS_OVERWRITEPROMPT = 0x00000002, FOS_STRICTFILETYPES = 0x00000004, FOS_NOCHANGEDIR = 0x00000008, FOS_PICKFOLDERS = 0x00000020, FOS_FORCEFILESYSTEM = 0x00000040, // Ensure that items returned are filesystem items. FOS_ALLNONSTORAGEITEMS = 0x00000080, // Allow choosing items that have no storage. FOS_NOVALIDATE = 0x00000100, FOS_ALLOWMULTISELECT = 0x00000200, FOS_PATHMUSTEXIST = 0x00000800, FOS_FILEMUSTEXIST = 0x00001000, FOS_CREATEPROMPT = 0x00002000, FOS_SHAREAWARE = 0x00004000, FOS_NOREADONLYRETURN = 0x00008000, FOS_NOTESTFILECREATE = 0x00010000, FOS_HIDEMRUPLACES = 0x00020000, FOS_HIDEPINNEDPLACES = 0x00040000, FOS_NODEREFERENCELINKS = 0x00100000, FOS_DONTADDTORECENT = 0x02000000, FOS_FORCESHOWHIDDEN = 0x10000000, FOS_DEFAULTNOMINIMODE = 0x20000000 } internal enum SIATTRIBFLAGS { SIATTRIBFLAGS_AND = 1, SIATTRIBFLAGS_APPCOMPAT = 3, SIATTRIBFLAGS_OR = 2 } internal enum SIGDN : uint { SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000, SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000, SIGDN_FILESYSPATH = 0x80058000, SIGDN_NORMALDISPLAY = 0, SIGDN_PARENTRELATIVE = 0x80080001, SIGDN_PARENTRELATIVEEDITING = 0x80031001, SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001, SIGDN_PARENTRELATIVEPARSING = 0x80018001, SIGDN_URL = 0x80068000 } #endregion Internal Enums #region 公共属性 /// <summary> /// 文件 /// </summary> public string Folder { get ; set ; } /// <summary> /// 标题 /// </summary> public string Title { get ; set ; } #endregion 公共属性 #region 公共方法 /// <summary> /// 显示对话框架 /// </summary> /// <param name="owner"></param> /// <returns></returns> public DialogResult ShowDialog(IWin32Window owner = null ) { IntPtr hwndOwner = owner != null ? owner.Handle : NativeMethods.GetActiveWindow(); NativeInterfaces.IFileOpenDialog dialog = (NativeInterfaces.IFileOpenDialog) new FileOpenDialog(); try { if (! string .IsNullOrEmpty(Folder)) { if (!IsValidFolderPath(Folder)) { // 提示用户文件夹路径无效 MessageBox.Show( "无效的文件夹路径,请重新选择。" , "错误" , MessageBoxButtons.OK, MessageBoxIcon.Error); return DialogResult.Cancel; } Guid _shellItemGuid = typeof (NativeInterfaces.IShellItem).GUID; NativeInterfaces.IShellItem item = (NativeInterfaces.IShellItem)NativeMethods.SHCreateItemFromParsingName(Folder, null , ref _shellItemGuid); if (item != null ) dialog.SetFolder(item); } dialog.SetOptions(FOS.FOS_PICKFOLDERS | FOS.FOS_FORCEFILESYSTEM); if (! string .IsNullOrEmpty(Title)) dialog.SetTitle(Title); int hr = dialog.Show(hwndOwner); if (hr == NativeMethods.ERROR_CANCELLED) return DialogResult.Cancel; if (hr != 0) return DialogResult.Abort; NativeInterfaces.IShellItem resultItem; dialog.GetResult( out resultItem); resultItem.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out string path); Folder = path; return DialogResult.OK; } catch (Exception ex) { // 处理异常 MessageBox.Show($ "发生错误:{ex.Message}" , "错误" , MessageBoxButtons.OK, MessageBoxIcon.Error); return DialogResult.Abort; } } private bool IsValidFolderPath( string folderPath) { // 这里可以添加更复杂的逻辑来验证文件夹路径的有效性 // 例如,检查文件夹是否存在,是否可访问等 return Directory.Exists(folderPath); } #endregion 公共方法 #region Internal Structs [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)] internal struct COMDLG_FILTERSPEC { [MarshalAs(UnmanagedType.LPWStr)] public string pszName; [MarshalAs(UnmanagedType.LPWStr)] public string pszSpec; } [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct PROPERTYKEY { public Guid fmtid; public uint pid; } #endregion Internal Structs #region Internal Classes internal static class NativeInterfaces { #region Public Interfaces [ComImport, Guid( "42f85136-db7e-439c-85f1-e4075d135fc8" ), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IFileDialog : IModalWindow { [PreserveSig] new int Show([In] IntPtr parent); void SetFileTypes([In] uint cFileTypes, [In][MarshalAs(UnmanagedType.LPArray)] COMDLG_FILTERSPEC[] rgFilterSpec); void SetFileTypeIndex([In] uint iFileType); void GetFileTypeIndex( out uint piFileType); void Advise([In, MarshalAs(UnmanagedType.Interface)] IFileDialogEvents pfde, out uint pdwCookie); void Unadvise([In] uint dwCookie); void SetOptions([In] FOS fos); void GetOptions( out FOS pfos); void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi); void SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi); void GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); void GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); void SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName); void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName); void SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle); void SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText); void SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel); void GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); void AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, int alignment); void SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension); void Close([MarshalAs(UnmanagedType.Error)] int hr); void SetClientGuid([In] ref Guid guid); void ClearClientData(); void SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter); } [ComImport, Guid( "973510DB-7D7F-452B-8975-74A85828D354" ), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IFileDialogEvents { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] int OnFileOk([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] int OnFolderChanging([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd, [In, MarshalAs(UnmanagedType.Interface)] IShellItem psiFolder); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void OnFolderChange([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void OnSelectionChange([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void OnShareViolation([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd, [In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, out FDE_SHAREVIOLATION_RESPONSE pResponse); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void OnTypeChange([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void OnOverwrite([In, MarshalAs(UnmanagedType.Interface)] IFileDialog pfd, [In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, out FDE_OVERWRITE_RESPONSE pResponse); } [ComImport, Guid( "d57c7288-d4ad-4768-be02-9d969532d960" ), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IFileOpenDialog : IFileDialog { void AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, FileDialogCustomPlace fdcp); void GetResults([MarshalAs(UnmanagedType.Interface)] out IShellItemArray ppenum); void GetSelectedItems([MarshalAs(UnmanagedType.Interface)] out IShellItemArray ppsai); } [ComImport, Guid( "b4db1657-70d7-485e-8e3e-6fcb5a5c1802" ), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IModalWindow { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] uint Show([In] IntPtr parent); } [ComImport, Guid( "43826D1E-E718-42EE-BC55-A1E261C37BFE" ), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IShellItem { void BindToHandler([In, MarshalAs(UnmanagedType.Interface)] IntPtr pbc, [In] ref Guid bhid, [In] ref Guid riid, out IntPtr ppv); void GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); void GetDisplayName([In] SIGDN sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName); void GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs); void Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder); } [ComImport, Guid( "B63EA76D-1F85-456F-A19C-48159EFA858B" ), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IShellItemArray { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void BindToHandler([In, MarshalAs(UnmanagedType.Interface)] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, out IntPtr ppvOut); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetPropertyStore([In] int Flags, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetPropertyDescriptionList([In] ref PROPERTYKEY keyType, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAttributes([In] SIATTRIBFLAGS dwAttribFlags, [In] uint sfgaoMask, out uint psfgaoAttribs); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetCount( out uint pdwNumItems); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetItemAt([In] uint dwIndex, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void EnumItems([MarshalAs(UnmanagedType.Interface)] out IntPtr ppenumShellItems); } #endregion Public Interfaces } [SuppressUnmanagedCodeSecurity] internal static class NativeMethods { #region Public Fields public const int ERROR_CANCELLED = unchecked (( int )0x800704C7); #endregion Public Fields #region Public Methods [DllImport( "user32.dll" )] public static extern IntPtr GetActiveWindow(); [DllImport( "shell32.dll" , SetLastError = true , CharSet = CharSet.Unicode, PreserveSig = false )] [ return : MarshalAs(UnmanagedType.Interface)] public static extern object SHCreateItemFromParsingName( [MarshalAs(UnmanagedType.LPWStr)] string pszPath, IBindCtx pbc, ref Guid riid); #endregion Public Methods } #endregion Internal Classes #region Private Classes [ComImport, Guid( "DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7" )] private class FileOpenDialog { } #endregion Private Classes } |
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2021-06-25 C# 深拷贝(新赋值对象不使用原来的对象内存地址)
2021-06-25 C# WinForm 自定义控件绑定属性DataBindings