- Общие сведения о компоненте FolderBrowserDialog (Windows Forms) FolderBrowserDialog Component Overview (Windows Forms)
- Folder Browser Dialog Класс
- Определение
- Примеры
- Комментарии
- Конструкторы
- Свойства
- Методы
- События
- Folder Browser Dialog. Root Folder Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
- Folder Browser Dialog Class
- Definition
- Examples
- Remarks
- Constructors
- Properties
- Methods
- Events
Общие сведения о компоненте FolderBrowserDialog (Windows Forms) FolderBrowserDialog Component Overview (Windows Forms)
Windows Forms FolderBrowserDialog компонент является модальным диалоговым окном, используемым для обзора и выбора папок. The Windows Forms FolderBrowserDialog component is a modal dialog box that is used for browsing and selecting folders. В компоненте также можно создавать новые папки FolderBrowserDialog . New folders can also be created from within the FolderBrowserDialog component.
Для выбора файлов вместо папок используйте компонент OpenFileDialog . To select files, instead of folders, use the OpenFileDialog component.
FolderBrowserDialogКомпонент отображается во время выполнения с помощью ShowDialog метода. The FolderBrowserDialog component is displayed at run time using the ShowDialog method. Задайте RootFolder свойство, чтобы определить самую верхнюю папку и все вложенные папки, которые будут отображаться в представлении в виде дерева диалогового окна. Set the RootFolder property to determine the top-most folder and any subfolders that will appear within the tree view of the dialog box. После отображения диалогового окна можно использовать SelectedPath свойство, чтобы получить путь к выбранной папке. Once the dialog box has been shown, you can use the SelectedPath property to get the path of the folder that was selected.
При добавлении в форму FolderBrowserDialog компонент отображается в области в нижней части конструктор Windows Forms в Visual Studio. When it is added to a form, the FolderBrowserDialog component appears in the tray at the bottom of the Windows Forms Designer in Visual Studio.
Folder Browser Dialog Класс
Определение
Выдает приглашение пользователю для выбора папки. Prompts the user to select a folder. Этот класс не наследуется. This class cannot be inherited.
Примеры
В следующем примере кода создается приложение, позволяющее пользователю открывать форматированные текстовые файлы (RTF) в RichTextBox элементе управления. The following code example creates an application that enables the user to open rich text (.rtf) files within the RichTextBox control.
Комментарии
Этот класс предоставляет способ запроса пользователя на просмотр, создание и в конечном итоге выбор папки. This class provides a way to prompt the user to browse, create, and eventually select a folder. Используйте этот класс, если вы хотите разрешить пользователю выбирать только папки, а не файлы. Use this class when you only want to allow the user to select folders, not files. Просмотр папок осуществляется с помощью элемента управления «дерево». Browsing of the folders is done through a tree control. Можно выбрать только папки из файловой системы. виртуальные папки не могут быть. Only folders from the file system can be selected; virtual folders cannot.
Как правило, после создания новой учетной FolderBrowserDialog области задается RootFolder расположение, из которого начинается просмотр. Typically, after creating a new FolderBrowserDialog, you set the RootFolder to the location from which to start browsing. При необходимости можно задать для параметра значение SelectedPath абсолютный путь к вложенной папке RootFolder , которая изначально будет выбрана. Optionally, you can set the SelectedPath to an absolute path of a subfolder of RootFolder that will initially be selected. При необходимости можно также задать свойство, Description чтобы предоставить пользователю дополнительные инструкции. You can also optionally set the Description property to provide additional instructions to the user. Наконец, вызовите ShowDialog метод, чтобы отобразить диалоговое окно для пользователя. Finally, call the ShowDialog method to display the dialog box to the user. Когда диалоговое окно закрывается, а результатом диалогового окна ShowDialog является значение DialogResult.OK , это SelectedPath будет строка, содержащая путь к выбранной папке. When the dialog box is closed and the dialog box result from ShowDialog is DialogResult.OK, the SelectedPath will be a string containing the path to the selected folder.
Свойство можно использовать для управления тем, может ShowNewFolderButton ли пользователь создавать новые папки с помощью кнопки создать папку . You can use the ShowNewFolderButton property to control if the user is able to create new folders with the New Folder button.
FolderBrowserDialog является модальным диалоговым окном; Таким образом, если он показан, он блокирует остальную часть приложения, пока пользователь не выберет папку. FolderBrowserDialog is a modal dialog box; therefore, when shown, it blocks the rest of the application until the user has chosen a folder. При отображении диалогового окна в модальном режиме входные данные (нажатие клавиши или мыши) не могут быть выполнены, за исключением объектов в диалоговом окне. When a dialog box is displayed modally, no input (keyboard or mouse click) can occur except to objects on the dialog box. Программа должна скрыть или закрыть диалоговое окно (обычно в ответ на какое-либо действие пользователя), прежде чем может произойти ввод в вызывающую программу. The program must hide or close the dialog box (usually in response to some user action) before input to the calling program can occur.
Конструкторы
Инициализирует новый экземпляр класса FolderBrowserDialog. Initializes a new instance of the FolderBrowserDialog class.
Свойства
Возвращает или задает значение, указывающее, будет ли диалоговое окно автоматически обновлено для включения новых функций. Gets or sets a value that indicates whether the dialog will be automatically upgraded to enable new features.
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.
(Унаследовано от Component)
Получает или задает описательный текст, отображаемый над элементом управления деревом в диалоговом окне. Gets or sets the descriptive text displayed above the tree view control in the dialog box.
Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.
(Унаследовано от Component)
Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.
(Унаследовано от Component)
Получает или задает корневую папку, с которой начинается просмотр. Gets or sets the root folder where the browsing starts from.
Получает или задает путь, выбранный пользователем. Gets or sets the path selected by the user.
Получает или задает значение, указывающее, отображается ли кнопка Создать папку в диалоговом окне обозревателя папок. Gets or sets a value indicating whether the New Folder button appears in the folder browser dialog box.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Получает или задает объект, содержащий данные элемента управления. Gets or sets an object that contains data about the control.
(Унаследовано от CommonDialog)
Возвращает или задает значение, указывающее, следует ли использовать значение свойства Description в качестве заголовка диалогового окна для диалоговых окон в стиле Vista. Gets or sets a value that indicates whether to use the value of the Description property as the dialog title for Vista style dialogs. Это свойство не влияет на диалоговые окна в старом стиле. This property has no effect on old style dialogs.
Методы
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Унаследовано от MarshalByRefObject)
Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.
(Унаследовано от Component)
Освобождает неуправляемые ресурсы, используемые объектом Component, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the Component and optionally releases the managed resources.
(Унаследовано от Component)
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.
(Унаследовано от Component)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Определяет процедуру обработки общего диалогового окна, переопределенную, чтобы добавить специальные функции для общего диалогового окна. Defines the common dialog box hook procedure that is overridden to add specific functionality to a common dialog box.
(Унаследовано от CommonDialog)
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.
(Унаследовано от MarshalByRefObject)
Вызывает событие HelpRequest. Raises the HelpRequest event.
(Унаследовано от CommonDialog)
Определяет процедуру окна-владельца, которая переопределяется, чтобы добавить специальные функции для общего диалогового окна. Defines the owner window procedure that is overridden to add specific functionality to a common dialog box.
(Унаследовано от CommonDialog)
Восстанавливает значения свойств по умолчанию. Resets properties to their default values.
В случае переопределения в производном классе указывает общее диалоговое окно. When overridden in a derived class, specifies a common dialog box.
(Унаследовано от CommonDialog)
Запускает общее диалоговое окно с заданным по умолчанию владельцем. Runs a common dialog box with a default owner.
(Унаследовано от CommonDialog)
Запускает общее диалоговое окно с указанным владельцем. Runs a common dialog box with the specified owner.
(Унаследовано от CommonDialog)
Возвращает объект String, содержащий имя Component, если оно есть. Returns a String containing the name of the Component, if any. Этот метод не следует переопределять. This method should not be overridden.
(Унаследовано от Component)
События
Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.
(Унаследовано от Component)
Происходит при нажатии пользователем кнопки Help в диалоговом окне. Occurs when the user clicks the Help button on the dialog box.
Folder Browser Dialog. Root Folder Свойство
Определение
Получает или задает корневую папку, с которой начинается просмотр. Gets or sets the root folder where the browsing starts from.
Значение свойства
Одно из значений перечисления Environment.SpecialFolder. One of the Environment.SpecialFolder values. Значение по умолчанию — Desktop . The default is Desktop .
Исключения
Назначенное значение не является одном из значений Environment.SpecialFolder. The value assigned is not one of the Environment.SpecialFolder values.
Примеры
В следующем примере кода создается приложение, позволяющее пользователю открывать форматированные текстовые файлы (RTF) в RichTextBox элементе управления. The following code example creates an application that enables the user to open rich text (.rtf) files within the RichTextBox control.
Комментарии
Только указанная папка и все вложенные в нее папки будут отображаться в диалоговом окне и доступны для выбора. Only the specified folder and any subfolders that are beneath it will appear in the dialog box and be selectable. SelectedPathСвойство вместе с RootFolder определяет, что будет выбранная папка при отображении диалогового окна, если SelectedPath является абсолютным путем, который является вложенной папкой RootFolder (или точнее, указывает на вложенную папку пространства имен оболочки, представленного параметром RootFolder ). The SelectedPath property, along with RootFolder, determines what the selected folder will be when the dialog box is displayed, as long as SelectedPath is an absolute path that is a subfolder of RootFolder (or more accurately, points to a subfolder of the shell namespace represented by RootFolder).
Folder Browser Dialog Class
Definition
Prompts the user to select a folder. This class cannot be inherited.
Examples
The following code example creates an application that enables the user to open rich text (.rtf) files within the RichTextBox control.
Remarks
This class provides a way to prompt the user to browse, create, and eventually select a folder. Use this class when you only want to allow the user to select folders, not files. Browsing of the folders is done through a tree control. Only folders from the file system can be selected; virtual folders cannot.
Typically, after creating a new FolderBrowserDialog, you set the RootFolder to the location from which to start browsing. Optionally, you can set the SelectedPath to an absolute path of a subfolder of RootFolder that will initially be selected. You can also optionally set the Description property to provide additional instructions to the user. Finally, call the ShowDialog method to display the dialog box to the user. When the dialog box is closed and the dialog box result from ShowDialog is DialogResult.OK, the SelectedPath will be a string containing the path to the selected folder.
You can use the ShowNewFolderButton property to control if the user is able to create new folders with the New Folder button.
FolderBrowserDialog is a modal dialog box; therefore, when shown, it blocks the rest of the application until the user has chosen a folder. When a dialog box is displayed modally, no input (keyboard or mouse click) can occur except to objects on the dialog box. The program must hide or close the dialog box (usually in response to some user action) before input to the calling program can occur.
Constructors
Initializes a new instance of the FolderBrowserDialog class.
Properties
Gets or sets a value that indicates whether the dialog will be automatically upgraded to enable new features.
Gets a value indicating whether the component can raise an event.
(Inherited from Component)
Gets the IContainer that contains the Component.
(Inherited from Component)
Gets or sets the descriptive text displayed above the tree view control in the dialog box.
Gets a value that indicates whether the Component is currently in design mode.
(Inherited from Component)
Gets the list of event handlers that are attached to this Component.
(Inherited from Component)
Gets or sets the root folder where the browsing starts from.
Gets or sets the path selected by the user.
Gets or sets a value indicating whether the New Folder button appears in the folder browser dialog box.
Gets or sets the ISite of the Component.
(Inherited from Component)
Gets or sets an object that contains data about the control.
(Inherited from CommonDialog)
Gets or sets a value that indicates whether to use the value of the Description property as the dialog title for Vista style dialogs. This property has no effect on old style dialogs.
Methods
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Inherited from MarshalByRefObject)
Releases all resources used by the Component.
(Inherited from Component)
Releases the unmanaged resources used by the Component and optionally releases the managed resources.
(Inherited from Component)
Determines whether the specified object is equal to the current object.
(Inherited from Object)
Serves as the default hash function.
(Inherited from Object)
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Returns an object that represents a service provided by the Component or by its Container.
(Inherited from Component)
Gets the Type of the current instance.
(Inherited from Object)
Defines the common dialog box hook procedure that is overridden to add specific functionality to a common dialog box.
(Inherited from CommonDialog)
Obtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Creates a shallow copy of the current Object.
(Inherited from Object)
Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject)
Raises the HelpRequest event.
(Inherited from CommonDialog)
Defines the owner window procedure that is overridden to add specific functionality to a common dialog box.
(Inherited from CommonDialog)
Resets properties to their default values.
When overridden in a derived class, specifies a common dialog box.
(Inherited from CommonDialog)
Runs a common dialog box with a default owner.
(Inherited from CommonDialog)
Runs a common dialog box with the specified owner.
(Inherited from CommonDialog)
Returns a String containing the name of the Component, if any. This method should not be overridden.
(Inherited from Component)
Events
Occurs when the component is disposed by a call to the Dispose() method.
(Inherited from Component)
Occurs when the user clicks the Help button on the dialog box.