VB.NET 中调用浏览目录对话框

VB.NET 中调用浏览目录对话框

Montaque

概述:

我们都知道在 .NET 中调用一个打开文件的对话框很容易,定义一个 OpenFileDialog 类的实例就可以直接使用了。有时候我们需要让用户选择一个工作目录,或者一个系统目录,于是就在搜索是不是有类似的 OpenDirectoryDialog 类呢?当然最好有一个,这样就很方便了。其实系统并没有提供这么一个类,下面我们就采用很短的代码构建这个目录浏览对话框。

思想:

在项目的引用中,浏览一下,会发现有一个 System.Designer.dll, 默认这个 dll 并没有被项目引用,我们今天就把它引到项目中。在 System.Windows.Forms.Design 这个名控件下面有一个 FolderNameEditor 类,其实就是一个目录浏览对话框,只不过这个类不能直接使用,必须 Inherit 。看下面的代码:

为了模块化,我们在项目中新建一个 class ,命名为 OpenDirectoryDialog ,输入类似下面的代码:

代码:

Imports System.Windows.Forms

Public Class FolderBrowser

Inherits System.Windows.Forms.Design.FolderNameEditor

Public Shared Function ShowDialog() As String

Dim fb As New FolderBrowser()

' 对话框的 title

fb.Description = "Select a Directory to Scan"

' 默认是系统的桌面目录

fb.StartLocation = Design.FolderNameEditor.FolderBrowserFolder.Desktop

' 对话框的样式

fb.Style = Design.FolderNameEditor.FolderBrowserStyles.ShowTextBox

fb.ShowDialog()

Return fb.DirectoryPath

End Function

End Class


编译好以后,我们就可以直接用这个 Class 了。

调用如下:

Debug.WriteLine(OpenDirectoryDialog.ShowDialog())

我们将看到下面的对话框:

参考: ms-help://MS.VSCC/MS.MSDNVS.2052/cpref/html/frlrfsystemwindowsformsdesignfoldernameeditorclasstopic.htm

Published At
Categories with Web编程
Tagged with
comments powered by Disqus