FolderBrowserDialog 类

定义

提示用户选择文件夹。 此类不能被继承。

public ref class FolderBrowserDialog sealed : System::Windows::Forms::CommonDialog
public sealed class FolderBrowserDialog : System.Windows.Forms.CommonDialog
type FolderBrowserDialog = class
    inherit CommonDialog
Public NotInheritable Class FolderBrowserDialog
Inherits CommonDialog
继承

示例

下面的代码示例创建一个应用程序,使用户能够打开控件中的 RichTextBox 文件 (.rtf) 格式文本。

// The following example displays an application that provides the ability to
// open rich text files (rtf) into the RichTextBox. The example demonstrates
// using the FolderBrowserDialog to set the default directory for opening files.
// The OpenFileDialog is used to open the file.
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System::IO;
public ref class FolderBrowserDialogExampleForm: public System::Windows::Forms::Form
{
private:
   FolderBrowserDialog^ folderBrowserDialog1;
   OpenFileDialog^ openFileDialog1;
   RichTextBox^ richTextBox1;
   MainMenu^ mainMenu1;
   MenuItem^ fileMenuItem;
   MenuItem^ openMenuItem;
   MenuItem^ folderMenuItem;
   MenuItem^ closeMenuItem;
   String^ openFileName;
   String^ folderName;
   bool fileOpened;

public:

   // Constructor.
   FolderBrowserDialogExampleForm()
   {
      fileOpened = false;
      this->mainMenu1 = gcnew System::Windows::Forms::MainMenu;
      this->fileMenuItem = gcnew System::Windows::Forms::MenuItem;
      this->openMenuItem = gcnew System::Windows::Forms::MenuItem;
      this->folderMenuItem = gcnew System::Windows::Forms::MenuItem;
      this->closeMenuItem = gcnew System::Windows::Forms::MenuItem;
      this->openFileDialog1 = gcnew System::Windows::Forms::OpenFileDialog;
      this->folderBrowserDialog1 = gcnew System::Windows::Forms::FolderBrowserDialog;
      this->richTextBox1 = gcnew System::Windows::Forms::RichTextBox;
      this->mainMenu1->MenuItems->Add( this->fileMenuItem );
      array<System::Windows::Forms::MenuItem^>^temp0 = {this->openMenuItem,this->closeMenuItem,this->folderMenuItem};
      this->fileMenuItem->MenuItems->AddRange( temp0 );
      this->fileMenuItem->Text = "File";
      this->openMenuItem->Text = "Open...";
      this->openMenuItem->Click += gcnew System::EventHandler( this, &FolderBrowserDialogExampleForm::openMenuItem_Click );
      this->folderMenuItem->Text = "Select Directory...";
      this->folderMenuItem->Click += gcnew System::EventHandler( this, &FolderBrowserDialogExampleForm::folderMenuItem_Click );
      this->closeMenuItem->Text = "Close";
      this->closeMenuItem->Click += gcnew System::EventHandler( this, &FolderBrowserDialogExampleForm::closeMenuItem_Click );
      this->closeMenuItem->Enabled = false;
      this->openFileDialog1->DefaultExt = "rtf";
      this->openFileDialog1->Filter = "rtf files (*.rtf)|*.rtf";
      
      // Set the help text description for the FolderBrowserDialog.
      this->folderBrowserDialog1->Description = "Select the directory that you want to use as the default.";
      
      // Do not allow the user to create new files via the FolderBrowserDialog.
      this->folderBrowserDialog1->ShowNewFolderButton = false;
      
      // Default to the My Documents folder.
      this->folderBrowserDialog1->RootFolder = Environment::SpecialFolder::Personal;
      this->richTextBox1->AcceptsTab = true;
      this->richTextBox1->Location = System::Drawing::Point( 8, 8 );
      this->richTextBox1->Size = System::Drawing::Size( 280, 344 );
      this->richTextBox1->Anchor = static_cast<AnchorStyles>(AnchorStyles::Top | AnchorStyles::Left | AnchorStyles::Bottom | AnchorStyles::Right);
      this->ClientSize = System::Drawing::Size( 296, 360 );
      this->Controls->Add( this->richTextBox1 );
      this->Menu = this->mainMenu1;
      this->Text = "RTF Document Browser";
   }


private:

   // Bring up a dialog to open a file.
   void openMenuItem_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      
      // If a file is not opened then set the initial directory to the
      // FolderBrowserDialog::SelectedPath value.
      if (  !fileOpened )
      {
         openFileDialog1->InitialDirectory = folderBrowserDialog1->SelectedPath;
         openFileDialog1->FileName = nullptr;
      }

      
      // Display the openFile Dialog.
      System::Windows::Forms::DialogResult result = openFileDialog1->ShowDialog();
      
      // OK button was pressed.
      if ( result == ::DialogResult::OK )
      {
         openFileName = openFileDialog1->FileName;
         try
         {
            
            // Output the requested file in richTextBox1.
            Stream^ s = openFileDialog1->OpenFile();
            richTextBox1->LoadFile( s, RichTextBoxStreamType::RichText );
            s->Close();
            fileOpened = true;
         }
         catch ( Exception^ exp ) 
         {
            MessageBox::Show( String::Concat( "An error occurred while attempting to load the file. The error is: ", System::Environment::NewLine, exp, System::Environment::NewLine ) );
            fileOpened = false;
         }

         Invalidate();
         closeMenuItem->Enabled = fileOpened;
      }
      // Cancel button was pressed.
      else
      
      // Cancel button was pressed.
      if ( result == ::DialogResult::Cancel )
      {
         return;
      }
   }


   // Close the current file.
   void closeMenuItem_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      richTextBox1->Text = "";
      fileOpened = false;
      closeMenuItem->Enabled = false;
   }


   // Bring up a dialog to chose a folder path in which to open/save a file.
   void folderMenuItem_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      
      // Show the FolderBrowserDialog.
      System::Windows::Forms::DialogResult result = folderBrowserDialog1->ShowDialog();
      if ( result == ::DialogResult::OK )
      {
         folderName = folderBrowserDialog1->SelectedPath;
         if (  !fileOpened )
         {
            
            // No file is opened, bring up openFileDialog in selected path.
            openFileDialog1->InitialDirectory = folderName;
            openFileDialog1->FileName = nullptr;
            openMenuItem->PerformClick();
         }
      }
   }

};


// The main entry point for the application.
int main()
{
   Application::Run( gcnew FolderBrowserDialogExampleForm );
}
// The following example displays an application that provides the ability to 
// open rich text files (rtf) into the RichTextBox. The example demonstrates 
// using the FolderBrowserDialog to set the default directory for opening files.
// The OpenFileDialog class is used to open the file.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

public class FolderBrowserDialogExampleForm : System.Windows.Forms.Form
{
    private FolderBrowserDialog folderBrowserDialog1;
    private OpenFileDialog openFileDialog1;

    private RichTextBox richTextBox1;

    private MenuStrip mainMenu1;
    private ToolStripMenuItem fileMenuItem, openMenuItem;
    private ToolStripMenuItem folderMenuItem, closeMenuItem;

    private string openFileName, folderName;

    private bool fileOpened = false;

    // The main entry point for the application.
    [STAThreadAttribute]
    static void Main()
    {
        Application.Run(new FolderBrowserDialogExampleForm());
    }

    // Constructor.
    public FolderBrowserDialogExampleForm()
    {
        this.mainMenu1 = new MenuStrip();

        this.fileMenuItem = new ToolStripMenuItem();
        this.openMenuItem = new ToolStripMenuItem();
        this.folderMenuItem = new ToolStripMenuItem();
        this.closeMenuItem = new ToolStripMenuItem();

        this.openFileDialog1 = new OpenFileDialog();
        this.folderBrowserDialog1 = new FolderBrowserDialog();
        this.richTextBox1 = new RichTextBox();

        this.mainMenu1.Items.Add(this.fileMenuItem);

        this.fileMenuItem.Text = "File";
        this.fileMenuItem.DropDownItems.AddRange(
            new ToolStripItem[] {
                this.openMenuItem,
                this.closeMenuItem,
                this.folderMenuItem
            }
        );

        this.openMenuItem.Text = "Open...";
        this.openMenuItem.Click += new EventHandler(this.openMenuItem_Click);

        this.folderMenuItem.Text = "Select Directory...";
        this.folderMenuItem.Click += new EventHandler(this.folderMenuItem_Click);

        this.closeMenuItem.Text = "Close";
        this.closeMenuItem.Click += new EventHandler(this.closeMenuItem_Click);
        this.closeMenuItem.Enabled = false;

        this.openFileDialog1.DefaultExt = "rtf";
        this.openFileDialog1.Filter = "rtf files (*.rtf)|*.rtf";

        // Set the help text description for the FolderBrowserDialog.
        this.folderBrowserDialog1.Description =
            "Select the directory that you want to use as the default.";

        // Do not allow the user to create new files via the FolderBrowserDialog.
        this.folderBrowserDialog1.ShowNewFolderButton = false;

        // Default to the My Documents folder.
        this.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;

        this.richTextBox1.AcceptsTab = true;
        this.richTextBox1.Location = new System.Drawing.Point(8, 40);
        this.richTextBox1.Size = new System.Drawing.Size(280, 312);
        this.richTextBox1.Anchor = (
            AnchorStyles.Top |
            AnchorStyles.Left |
            AnchorStyles.Bottom |
            AnchorStyles.Right
        );

        this.ClientSize = new System.Drawing.Size(296, 360);
        this.Controls.Add(this.mainMenu1);
        this.Controls.Add(this.richTextBox1);
        this.MainMenuStrip = this.mainMenu1;
        this.Text = "RTF Document Browser";
    }

    // Bring up a dialog to open a file.
    private void openMenuItem_Click(object sender, EventArgs e)
    {
        // If a file is not opened, then set the initial directory to the
        // FolderBrowserDialog.SelectedPath value.
        if (!fileOpened) {
            openFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath;
            openFileDialog1.FileName = null;
        }

        // Display the openFile dialog.
        DialogResult result = openFileDialog1.ShowDialog();

        // OK button was pressed.
        if (result == DialogResult.OK)
        {
            openFileName = openFileDialog1.FileName;
            try
            {
                // Output the requested file in richTextBox1.
                Stream s = openFileDialog1.OpenFile();
                richTextBox1.LoadFile(s, RichTextBoxStreamType.RichText);
                s.Close();

                fileOpened = true;
            }
            catch (Exception exp)
            {
                MessageBox.Show("An error occurred while attempting to load the file. The error is:"
                                + System.Environment.NewLine + exp.ToString() + System.Environment.NewLine);
                fileOpened = false;
            }
            Invalidate();

            closeMenuItem.Enabled = fileOpened;
        }

        // Cancel button was pressed.
        else if (result == DialogResult.Cancel)
        {
            return;
        }
    }

    // Close the current file.
    private void closeMenuItem_Click(object sender, EventArgs e)
    {
        richTextBox1.Text = "";
        fileOpened = false;

        closeMenuItem.Enabled = false;
    }

    // Bring up a dialog to choose a folder path in which to open or save a file.
    private void folderMenuItem_Click(object sender, EventArgs e)
    {
        // Show the FolderBrowserDialog.
        DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            folderName = folderBrowserDialog1.SelectedPath;
            if (!fileOpened)
            {
                // No file is opened, bring up openFileDialog in selected path.
                openFileDialog1.InitialDirectory = folderName;
                openFileDialog1.FileName = null;
                openMenuItem.PerformClick();
            }
        }
    }
}
' The following example displays an application that provides the ability to 
' open rich text files (rtf) into the RichTextBox. The example demonstrates 
' using the FolderBrowserDialog to set the default directory for opening files.
' The OpenFileDialog class is used to open the file.
Imports System.Drawing
Imports System.Windows.Forms
Imports System.IO

Public Class FolderBrowserDialogExampleForm 
    Inherits Form
    
    Private folderBrowserDialog1 As FolderBrowserDialog
    Private openFileDialog1 As OpenFileDialog 
    
    Private richTextBox1 As RichTextBox

    Private mainMenu1 As MainMenu
    Private fileMenuItem As MenuItem
    Private WithEvents folderMenuItem As MenuItem, _
                       closeMenuItem As MenuItem, _
                       openMenuItem As MenuItem
    
    Private openFileName As String, folderName As String

    Private fileOpened As Boolean = False

    Public Sub New()
        Me.mainMenu1 = New System.Windows.Forms.MainMenu() 
        Me.fileMenuItem = New System.Windows.Forms.MenuItem() 
        Me.openMenuItem = New System.Windows.Forms.MenuItem() 
        Me.folderMenuItem = New System.Windows.Forms.MenuItem() 
        Me.closeMenuItem = New System.Windows.Forms.MenuItem() 

        Me.openFileDialog1 = New System.Windows.Forms.OpenFileDialog() 
        Me.folderBrowserDialog1 = New System.Windows.Forms.FolderBrowserDialog() 
        Me.richTextBox1 = New System.Windows.Forms.RichTextBox() 

        Me.mainMenu1.MenuItems.Add(Me.fileMenuItem) 
        Me.fileMenuItem.MenuItems.AddRange( _
                    New System.Windows.Forms.MenuItem() {Me.openMenuItem, _
                                                         Me.closeMenuItem, _
                                                         Me.folderMenuItem}) 
        Me.fileMenuItem.Text = "File" 

        Me.openMenuItem.Text = "Open..." 

        Me.folderMenuItem.Text = "Select Directory..." 

        Me.closeMenuItem.Text = "Close" 
        Me.closeMenuItem.Enabled = False 

        Me.openFileDialog1.DefaultExt = "rtf" 
        Me.openFileDialog1.Filter = "rtf files (*.rtf)|*.rtf" 

        ' Set the Help text description for the FolderBrowserDialog.
        Me.folderBrowserDialog1.Description = _
            "Select the directory that you want to use As the default." 

        ' Do not allow the user to create New files via the FolderBrowserDialog.
        Me.folderBrowserDialog1.ShowNewFolderButton = False 

        ' Default to the My Documents folder.
        Me.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal 

        Me.richTextBox1.AcceptsTab = True 
        Me.richTextBox1.Location = New System.Drawing.Point(8, 8) 
        Me.richTextBox1.Size = New System.Drawing.Size(280, 344) 
        Me.richTextBox1.Anchor = AnchorStyles.Top Or AnchorStyles.Left Or _
                                 AnchorStyles.Bottom Or AnchorStyles.Right 

        Me.ClientSize = New System.Drawing.Size(296, 360) 
        Me.Controls.Add(Me.richTextBox1) 
        Me.Menu = Me.mainMenu1 
        Me.Text = "RTF Document Browser" 
    End Sub
    
    <STAThread()> _
    Shared Sub Main()
        Application.Run(New FolderBrowserDialogExampleForm())
    End Sub

    ' Bring up a dialog to open a file.
    Private Sub openMenuItem_Click(sender As object, e As System.EventArgs) _
        Handles openMenuItem.Click
        ' If a file is not opened, then set the initial directory to the
        ' FolderBrowserDialog.SelectedPath value.
        If (not fileOpened) Then
            openFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath 
            openFileDialog1.FileName = nothing 
        End If

        ' Display the openFile dialog.
        Dim result As DialogResult = openFileDialog1.ShowDialog() 

        ' OK button was pressed.
        If (result = DialogResult.OK) Then
            openFileName = openFileDialog1.FileName 
            Try
                ' Output the requested file in richTextBox1.
                Dim s As Stream = openFileDialog1.OpenFile() 
                richTextBox1.LoadFile(s, RichTextBoxStreamType.RichText) 
                s.Close()     
            
                fileOpened = True 

            Catch exp As Exception
                MessageBox.Show("An error occurred while attempting to load the file. The error is:" _
                                + System.Environment.NewLine + exp.ToString() + System.Environment.NewLine) 
                fileOpened = False 
            End Try
            Invalidate() 

            closeMenuItem.Enabled = fileOpened 

        ' Cancel button was pressed.
        ElseIf (result = DialogResult.Cancel) Then
            return 
        End If
    End Sub

    ' Close the current file.
    Private Sub closeMenuItem_Click(sender As object, e As System.EventArgs) _
        Handles closeMenuItem.Click
        richTextBox1.Text = "" 
        fileOpened = False 

        closeMenuItem.Enabled = False 
    End Sub

    ' Bring up a dialog to chose a folder path in which to open or save a file.
    Private Sub folderMenuItem_Click(sender As object, e As System.EventArgs) _
        Handles folderMenuItem.Click
        ' Show the FolderBrowserDialog.
        Dim result As DialogResult = folderBrowserDialog1.ShowDialog() 

        If ( result = DialogResult.OK ) Then
            folderName = folderBrowserDialog1.SelectedPath 
            If (not fileOpened) Then
                ' No file is opened, bring up openFileDialog in selected path.
                openFileDialog1.InitialDirectory = folderName 
                openFileDialog1.FileName = nothing
                openMenuItem.PerformClick() 
            End If
        End If
    End Sub

End Class

注解

此类提供了一种提示用户浏览、创建和最终选择文件夹的方法。 如果只想允许用户选择文件夹,而不是文件,请使用此类。 浏览文件夹是通过树控件完成的。 在 .NET Core 3.1 及更高版本中,此类使用现代化文件系统浏览器窗口。 只能选择文件系统中的文件夹;虚拟文件夹不能。

通常,在创建新 FolderBrowserDialog后,将 设置为 RootFolder 从中开始浏览的位置。 (可选)可以将 设置为 SelectedPath 最初将选择的子文件夹的 RootFolder 绝对路径。 还可以选择性地设置 Description 属性,向用户提供其他说明。 最后,调用 ShowDialog 方法向用户显示对话框。 当对话框关闭并且对话框结果为 ShowDialogDialogResult.OK时, SelectedPath 将是包含所选文件夹路径的字符串。

可以使用 ShowNewFolderButton 属性来控制用户是否能够使用“新建文件夹”按钮创建新 文件夹

FolderBrowserDialog 是模式对话框;因此,在显示时,它会阻止应用程序的其余部分,直到用户选择文件夹。 当对话框以模式显示时,除了对话框中的对象外,不会发生键盘 (输入或鼠标单击) 。 程序必须隐藏或关闭对话框 (通常响应某些用户操作) ,然后才能输入调用程序。

构造函数

FolderBrowserDialog()

初始化 FolderBrowserDialog 类的新实例。

属性

AddToRecent

获取或设置一个值,该值指示对话框是否将所选文件夹添加到最近列表。

AutoUpgradeEnabled

获取或设置一个值,该值指示是否自动升级对话框以启用新功能。

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。

(继承自 Component)
ClientGuid

获取或设置要与此对话状态关联的 GUID。 通常情况下,状态(如最后访问的文件夹)和对话框的位置及大小将根据可执行文件的名称持久保存。 通过指定 GUID,一个应用程序对于同一应用程序中不同版本的对话框(例如,导入的对话框和打开的对话框),可以具有不同的持久状态。

如果应用程序未使用视觉样式或如果 AutoUpgradeEnabled 设置为 false,则此功能不可用。

Container

获取包含 IContainerComponent

(继承自 Component)
Description

获取或设置对话框上方显示的描述性文本。

DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。

(继承自 Component)
Events

获取附加到此 Component 的事件处理程序的列表。

(继承自 Component)
InitialDirectory

获取或设置文件夹浏览器对话框显示的初始目录。

Multiselect

获取或设置一个值,该值指示对话框是否允许选择多个文件夹。

OkRequiresInteraction

获取或设置一个值,该值指示是否禁用对话框的“确定”按钮,直到用户导航视图或编辑文件名 ((如果适用) )。

RootFolder

获取或设置从其开始浏览的根文件夹。

SelectedPath

获取或设置用户选定的路径。

SelectedPaths

获取对话框中所有选定文件夹的路径。

ShowHiddenFiles

获取或设置一个值,该值指示对话框是否显示隐藏文件和系统文件。

ShowNewFolderButton

获取或设置一个值,该值指示“新建文件夹”按钮是否显示在文件夹浏览对话框中

ShowPinnedPlaces

获取或设置一个值,该值指示是否显示视图导航窗格中默认显示的项。

Site

获取或设置 ComponentISite

(继承自 Component)
Tag

获取或设置一个对象,该对象包含控件的数据。

(继承自 CommonDialog)
UseDescriptionForTitle

获取或设置一个值,该值指示是否将 Description 属性的值用作 Vista 样式对话框的标题。 此属性对旧样式对话框不起任何作用。

方法

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

(继承自 MarshalByRefObject)
Dispose()

释放由 Component 使用的所有资源。

(继承自 Component)
Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。

(继承自 Component)
Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。

(继承自 Component)
GetType()

获取当前实例的 Type

(继承自 Object)
HookProc(IntPtr, Int32, IntPtr, IntPtr)

定义要重写的通用对话框挂钩过程,以便向通用对话框添加特定功能。

(继承自 CommonDialog)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
OnHelpRequest(EventArgs)

引发 HelpRequest 事件。

(继承自 CommonDialog)
OwnerWndProc(IntPtr, Int32, IntPtr, IntPtr)

定义要重写的所有者窗口过程,以便向通用对话框添加特定功能。

(继承自 CommonDialog)
Reset()

将属性重置为其默认值。

RunDialog(IntPtr)

在派生类中被重写时,指定通用对话框。

(继承自 CommonDialog)
ShowDialog()

用默认的所有者运行通用对话框。

(继承自 CommonDialog)
ShowDialog(IWin32Window)

运行具有指定所有者的通用对话框。

(继承自 CommonDialog)
ToString()

返回包含 Component 的名称的 String(如果有)。 不应重写此方法。

(继承自 Component)

事件

Disposed

在通过调用 Dispose() 方法释放组件时发生。

(继承自 Component)
HelpRequest

当用户单击对话框中的“帮助”按钮时发生

适用于

另请参阅