- Элементы управления и компоненты диалоговых окон (Windows Forms) Dialog-Box Controls and Components (Windows Forms)
- Справочник Reference
- Связанные разделы Related Sections
- Form. Show Dialog Метод
- Определение
- Перегрузки
- ShowDialog()
- Возвращаемое значение
- Исключения
- Примеры
- Комментарии
- Form. Show Dialog Method
- Definition
- Overloads
- ShowDialog()
- Returns
- Exceptions
- Examples
- Remarks
- Диалоговые окна в Windows Forms Dialog Boxes in Windows Forms
- в этом разделе In This Section
- Связанные разделы Related Sections
- Open File Dialog Класс
- Определение
- Примеры
- Комментарии
- Конструкторы
- Свойства
- Методы
- События
Элементы управления и компоненты диалоговых окон (Windows Forms) Dialog-Box Controls and Components (Windows Forms)
Перечисленные ниже элементы управления и компоненты Windows Forms представляют стандартные диалоговые окна. The following Windows Forms controls and components present standard dialog boxes. Чтобы получить дополнительную информацию о функциях, доступных в каждом диалоговом окне, щелкните соответствующую ссылку. Follow the links for more information about the functions available in each dialog box.
Справочник Reference
ColorDialog
Справочная информация о классе ColorDialog и его членах. Provides reference information about the ColorDialog class and its members.
FontDialog
Справочная информация о классе FontDialog и его членах. Provides reference information about the FontDialog class and its members.
OpenFileDialog
Справочная информация о классе OpenFileDialog и его членах. Provides reference information about the OpenFileDialog class and its members.
PageSetupDialog
Справочная информация о классе PageSetupDialog и его членах. Provides reference information about the PageSetupDialog class and its members.
PrintDialog
Справочная информация о классе PrintDialog и его членах. Provides reference information about the PrintDialog class and its members.
PrintPreviewDialog
Справочная информация о классе PrintPreviewDialog и его членах. Provides reference information about the PrintPreviewDialog class and its members.
SaveFileDialog
Справочная информация о классе SaveFileDialog и его членах. Provides reference information about the SaveFileDialog class and its members.
Связанные разделы Related Sections
Диалоговые окна в Windows Forms Dialog Boxes in Windows Forms
Инструкции по созданию диалогового окна для формы Windows Forms. Describes how to create a dialog box for a Windows Form.
Общие сведения о компоненте ColorDialog ColorDialog Component Overview
Предоставляет стандартное диалоговое окно для выбора цветов из палитры и добавления в нее дополнительных цветов. Enables the user to select a color from a palette in a pre-configured dialog box and to add custom colors to that palette.
Общие сведения о компоненте FontDialog FontDialog Component Overview
Предоставляет приложениям шрифты, установленные в системе на текущий момент. Exposes the fonts that are currently installed on the system.
Общие сведения о компоненте OpenFileDialog OpenFileDialog Component Overview
Позволяет пользователям открывать файлы в стандартном диалоговом окне. Allows users to open files via a pre-configured dialog box.
Общие сведения о компоненте PageSetupDialog PageSetupDialog Component Overview
Предоставляет стандартное диалоговое окно для задания параметров страницы для печати. Sets page details for printing via a pre-configured dialog box.
Общие сведения о компоненте PrintDialog PrintDialog Component Overview
Служит для выбора принтера, печатаемых страниц и других параметров печати. Selects a printer, chooses the pages to print, and determines other print-related settings.
Общие сведения об элементе управления PrintPreviewDialog PrintPreviewDialog Control Overview
Выводит документ в том виде, как он будет выглядеть при печати. Displays a document as it will appear when it is printed.
Общие сведения о компоненте SaveFileDialog SaveFileDialog Component Overview
Служит для выбора сохраняемых файлов и места их сохранения. Selects files to save and where to save them.
Form. Show Dialog Метод
Определение
Отображает форму как модальное диалоговое окно. Shows the form as a modal dialog box.
Перегрузки
Отображает форму как модальное диалоговое окно. Shows the form as a modal dialog box.
Отображает эту форму в виде модального диалогового окна с указанным владельцем. Shows the form as a modal dialog box with the specified owner.
ShowDialog()
Отображает форму как модальное диалоговое окно. Shows the form as a modal dialog box.
Возвращаемое значение
Одно из значений перечисления DialogResult. One of the DialogResult values.
Исключения
Отображаемая форма уже отображена. The form being shown is already visible.
-или- -or- Отображаемая форма отключена. The form being shown is disabled.
-или- -or- Отображаемая форма не является окном верхнего уровня. The form being shown is not a top-level window.
-или- -or- Отображаемая в виде диалогового окна форма уже является модальной формой. The form being shown as a dialog box is already a modal form.
-или- -or- Текущий процесс не выполняется в интерактивном пользовательском режиме (дополнительные сведения см. в описании свойства UserInteractive). The current process is not running in user interactive mode (for more information, see UserInteractive).
Примеры
В следующем примере форма отображается как модальное диалоговое окно и вычисляет возвращаемое значение диалогового окна перед тем, как определить, следует ли считать значение TextBox элемента управления в форме диалогового окна. The following example displays a form as a modal dialog box and evaluates the return value of the dialog box before determining whether to read the value of a TextBox control on the dialog box form. В этом примере необходимо Form создать именованный объект, testDialog содержащий TextBox элемент управления с именем TextBox1 . This example requires that a Form named testDialog is created and that it contains a TextBox control named TextBox1 . Кроме того, в примере требуется, чтобы код в этом примере содержал и вызывался из другого Form списка, чтобы его можно было отобразить testDialog как модальное диалоговое окно. Furthermore, the example requires that code in this example is contained and called from a different Form in order to display testDialog as a modal dialog box. В примере используется версия ShowDialog , которая задает владельца для диалогового окна. The example uses the version of ShowDialog that specifies an owner for the dialog box.
Комментарии
Этот метод можно использовать для вывода модального диалогового окна в приложении. You can use this method to display a modal dialog box in your application. При вызове этого метода код, следующий за ним, не выполняется до тех пор, пока не будет закрыто диалоговое окно. When this method is called, the code following it is not executed until after the dialog box is closed. Диалоговому окну можно назначить одно из значений DialogResult перечисления, назначив его DialogResult свойству объекта Button в форме или задав DialogResult свойство формы в коде. The dialog box can be assigned one of the values of the DialogResult enumeration by assigning it to the DialogResult property of a Button on the form or by setting the DialogResult property of the form in code. Это значение затем возвращается этим методом. This value is then returned by this method. Это возвращаемое значение можно использовать для определения способа обработки действий, произошедших в диалоговом окне. You can use this return value to determine how to process the actions that occurred in the dialog box. Например, если диалоговое окно было закрыто и возвращено DialogResult.Cancel значение с помощью этого метода, можно предотвратить исполнение кода, следующего за вызовом ShowDialog . For example, if the dialog box was closed and returned the DialogResult.Cancel value through this method, you could prevent code following the call to ShowDialog from executing.
Когда форма отображается как модальное диалоговое окно, нажатие кнопки Закрыть (кнопка с крестиком в правом верхнем углу формы) приводит к скрытию формы и свойству, для которого DialogResult устанавливается значение DialogResult.Cancel . When a form is displayed as a modal dialog box, clicking the Close button (the button with an X at the upper-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel . В отличие от немодальных форм, Close метод не вызывается платформа .NET Framework, когда пользователь нажимает кнопку «Закрыть форму» диалогового окна или задает значение DialogResult Свойства. Unlike non-modal forms, the Close method is not called by the .NET Framework when the user clicks the close form button of a dialog box or sets the value of the DialogResult property. Вместо этого форма скрыта, и ее можно снова отобразить, не создавая новый экземпляр диалогового окна. Instead the form is hidden and can be shown again without creating a new instance of the dialog box. Так как форма, отображаемая как диалоговое окно, скрыта, а не закрыта, необходимо вызвать Dispose метод формы, если форма больше не нужна приложению. Because a form displayed as a dialog box is hidden instead of closed, you must call the Dispose method of the form when the form is no longer needed by your application.
Эта версия ShowDialog метода не указывает форму или элемент управления как владельца. This version of the ShowDialog method does not specify a form or control as its owner. При вызове этой версии текущее активное окно становится владельцем диалогового окна. When this version is called, the currently active window is made the owner of the dialog box. Если вы хотите указать конкретного владельца, используйте другую версию этого метода. If you want to specify a specific owner, use the other version of this method.
Form. Show Dialog Method
Definition
Shows the form as a modal dialog box.
Overloads
Shows the form as a modal dialog box.
Shows the form as a modal dialog box with the specified owner.
ShowDialog()
Shows the form as a modal dialog box.
Returns
One of the DialogResult values.
Exceptions
The form being shown is already visible.
The form being shown is disabled.
The form being shown is not a top-level window.
The form being shown as a dialog box is already a modal form.
The current process is not running in user interactive mode (for more information, see UserInteractive).
Examples
The following example displays a form as a modal dialog box and evaluates the return value of the dialog box before determining whether to read the value of a TextBox control on the dialog box form. This example requires that a Form named testDialog is created and that it contains a TextBox control named TextBox1 . Furthermore, the example requires that code in this example is contained and called from a different Form in order to display testDialog as a modal dialog box. The example uses the version of ShowDialog that specifies an owner for the dialog box.
Remarks
You can use this method to display a modal dialog box in your application. When this method is called, the code following it is not executed until after the dialog box is closed. The dialog box can be assigned one of the values of the DialogResult enumeration by assigning it to the DialogResult property of a Button on the form or by setting the DialogResult property of the form in code. This value is then returned by this method. You can use this return value to determine how to process the actions that occurred in the dialog box. For example, if the dialog box was closed and returned the DialogResult.Cancel value through this method, you could prevent code following the call to ShowDialog from executing.
When a form is displayed as a modal dialog box, clicking the Close button (the button with an X at the upper-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel . Unlike non-modal forms, the Close method is not called by the .NET Framework when the user clicks the close form button of a dialog box or sets the value of the DialogResult property. Instead the form is hidden and can be shown again without creating a new instance of the dialog box. Because a form displayed as a dialog box is hidden instead of closed, you must call the Dispose method of the form when the form is no longer needed by your application.
This version of the ShowDialog method does not specify a form or control as its owner. When this version is called, the currently active window is made the owner of the dialog box. If you want to specify a specific owner, use the other version of this method.
Диалоговые окна в Windows Forms Dialog Boxes in Windows Forms
Диалоговые окна используются для взаимодействия с пользователем и получения информации. Dialog boxes are used to interact with the user and retrieve information. Проще говоря, диалоговое окно представляет собой форму со значением ее свойства перечисления FormBorderStyle, установленным в FixedDialog . In simple terms, a dialog box is a form with its FormBorderStyle enumeration property set to FixedDialog . Пользовательские диалоговые окна можно создавать с помощью конструктор Windows Forms в Visual Studio. You can construct your own custom dialog boxes by using the Windows Forms Designer in Visual Studio. Для настройки диалоговых окон под конкретные потребности можно добавить элементы управления, такие как Label , Textbox и Button . Add controls such as Label , Textbox , and Button to customize dialog boxes to your specific needs. .NET Framework также содержит предопределенные диалоговые окна, такие как Открытие файлов и окна сообщений, которые можно адаптировать для собственных приложений. The .NET Framework also includes predefined dialog boxes, such as File Open and message boxes, which you can adapt for your own applications. Дополнительные сведения см. в разделе элементы управления и компоненты диалоговых окон. For more information, see Dialog-Box Controls and Components.
в этом разделе In This Section
Связанные разделы Related Sections
Элементы управления и компоненты диалоговых окон Dialog-Box Controls and Components
Список стандартных элементов управления диалоговых окон. Lists the predefined dialog box controls.
Изменение внешнего вида Windows Forms Changing the Appearance of Windows Forms
Содержит ссылки на разделы, описывающие, как изменить внешний вид приложений Windows Forms. Contains links to topics that describe how to change the appearance of Windows Forms applications.
Общие сведения об элементе управления TabControl TabControl Control Overview
Объясняется, как включить элемент управления «Вкладка» в диалоговое окно. Explains how you incorporate the tab control into a dialog box.
Open File Dialog Класс
Определение
Отображает диалоговое окно, позволяющее пользователю открыть файл. Displays a standard dialog box that prompts the user to open a file. Этот класс не наследуется. This class cannot be inherited.
Примеры
В следующем примере кода создается OpenFileDialog , задается несколько свойств, определяющих фильтр расширения файла и поведение диалогового окна, и отображается диалоговое окно с помощью CommonDialog.ShowDialog метода. The following code example creates an OpenFileDialog, sets several properties to define the file extension filter and dialog behavior, and displays the dialog box using the CommonDialog.ShowDialog method. Для примера требуется форма с Button помещенным на нее, а также ссылка на System.IO пространство имен, добавленное в нее. The example requires a form with a Button placed on it and a reference to the System.IO namespace added to it.
Комментарии
Этот класс позволяет проверить, существует ли файл, и открыть его. This class allows you to check whether a file exists and to open it. ShowReadOnlyСвойство определяет, отображается ли флажок только для чтения в диалоговом окне. The ShowReadOnly property determines whether a read-only check box appears in the dialog box. ReadOnlyCheckedСвойство указывает, установлен ли флажок только для чтения. The ReadOnlyChecked property indicates whether the read-only check box is checked.
Большая часть основных функций для этого класса находится в FileDialog классе. Most of the core functionality for this class is found in the FileDialog class.
В операционной системе с письмом справа налево установка свойства содержащей формы RightToLeft позволяет RightToLeft.Yes локализовать кнопки имя файла, Открыть и отменить диалоговые окна. On a right-to-left operating system, setting the containing form’s RightToLeft property to RightToLeft.Yes localizes the dialog’s File Name, Open, and Cancel buttons. Если свойство не имеет значение RightToLeft.Yes , вместо него используется текст на английском языке. If the property is not set to RightToLeft.Yes, English text is used instead.
Если вы хотите предоставить пользователю возможность выбрать папку вместо файла, используйте FolderBrowserDialog вместо нее. If you want to give the user the ability to select a folder instead of a file, use FolderBrowserDialog instead.
Конструкторы
Инициализирует экземпляр класса OpenFileDialog. Initializes an instance of the OpenFileDialog class.
Свойства
Возвращает или задает значение, определяющее, добавляет ли автоматически диалоговое окно расширение к имени файла, если пользователь опускает данное расширение. Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.
(Унаследовано от FileDialog)
Возвращает или задает значение, указывающее, должен ли этот FileDialog экземпляр автоматически обновлять внешний вид и поведение при работе в Windows Vista. Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and behavior when running on Windows Vista.
(Унаследовано от FileDialog)
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Возвращает или задает значение, указывающее, отображается ли в диалоговом окне предупреждение, если пользователь указывает несуществующее имя файла. Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.
Возвращает или задает значение, указывающее, отображает ли диалоговое окно предупреждение, если пользователь указывает несуществующий путь. Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.
(Унаследовано от FileDialog)
Получает или задает GUID, связываемый с этим состоянием диалога. Gets or sets the GUID to associate with this dialog state. Как правило, состояние, такое как последняя посещенная папка, а также расположение и размер диалогового окна, сохраняется с учетом имени исполняемого файла. Typically, state such as the last visited folder and the position and size of the dialog is persisted based on the name of the executable file. При указании GUID приложение может иметь разные сохраняемые состояния для разных версий диалогового окна в том же приложении (например, диалоговое окно импорта и диалоговое окно открытия). By specifying a GUID, an application can have different persisted states for different versions of the dialog within the same application (for example, an import dialog and an open dialog).
Эта функция недоступна, если приложение не использует стили оформления или если для AutoUpgradeEnabled задано значение false . This functionality is not available if an application is not using visual styles or if AutoUpgradeEnabled is set to false .
(Унаследовано от FileDialog)
Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.
(Унаследовано от Component)
Получает коллекцию пользовательских размещений для этого экземпляра FileDialog. Gets the custom places collection for this FileDialog instance.
(Унаследовано от FileDialog)
Возвращает или задает расширение имени файла по умолчанию. Gets or sets the default file name extension.
(Унаследовано от FileDialog)
Возвращает или задает значение, указывающее, возвращает ли диалоговое окно расположение файла, представленного ярлыком, или возвращает расположение самого ярлыка (.lnk). Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk).
(Унаследовано от FileDialog)
Возвращает значение, указывающее, находится ли данный компонент 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 a string containing the file name selected in the file dialog box.
(Унаследовано от FileDialog)
Возвращает имена всех выбранных файлов в диалоговом окне. Gets the file names of all selected files in the dialog box.
(Унаследовано от FileDialog)
Возвращает или задает текущую строку фильтра имен файлов, которая определяет варианты, доступные в поле диалогового окна «Сохранить как файл типа» или «Файлы типа». Gets or sets the current file name filter string, which determines the choices that appear in the «Save as file type» or «Files of type» box in the dialog box.
(Унаследовано от FileDialog)
Возвращает или задает индекс фильтра, выбранного в настоящий момент в диалоговом окне файла. Gets or sets the index of the filter currently selected in the file dialog box.
(Унаследовано от FileDialog)
Возвращает или задает начальную папку, отображенную диалоговым окном файла. Gets or sets the initial directory displayed by the file dialog box.
(Унаследовано от FileDialog)
Возвращает дескриптор экземпляра обработчика Win32 для приложения. Gets the Win32 instance handle for the application.
(Унаследовано от FileDialog)
Получает или задает значение, указывающее, можно ли в диалоговом окне выбирать несколько файлов. Gets or sets a value indicating whether the dialog box allows multiple files to be selected.
Получает значения для инициализации класса FileDialog. Gets values to initialize the FileDialog.
(Унаследовано от FileDialog)
Получает или задает значение, указывающее, установлен ли флажок доступности только для чтения. Gets or sets a value indicating whether the read-only check box is selected.
Получает или задает значение, указывающее, восстанавливает ли диалоговое окно ранее выбранный каталог в качестве текущего каталога перед закрытием. Gets or sets a value indicating whether the dialog box restores the directory to the previously selected directory before closing.
(Унаследовано от FileDialog)
Возвращает имя и расширение файла, выбранного в диалоговом окне. Gets the file name and extension for the file selected in the dialog box. Имя файла не включает сведения о пути. The file name does not include the path.
Возвращает массив имен и расширений файлов для всех выбранных в диалоговом окне файлов. Gets an array of file names and extensions for all the selected files in the dialog box. Имена файлов не включают сведений о пути. The file names do not include the path.
Возвращает или задает значение, определяющее, отображается ли кнопка Справка в диалоговом окне работы с файлами. Gets or sets a value indicating whether the Help button is displayed in the file dialog box.
(Унаследовано от FileDialog)
Получает или задает значение, указывающее, имеется ли в диалоговом окне флажок «доступно только для чтения». Gets or sets a value indicating whether the dialog box contains a read-only check box.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Возвращает или задает значение, определяющее, поддерживает ли диалоговое окно отображение и сохранение файлов, которые содержат несколько расширений имени. Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.
(Унаследовано от FileDialog)
Получает или задает объект, содержащий данные элемента управления. Gets or sets an object that contains data about the control.
(Унаследовано от CommonDialog)
Возвращает или задает заголовок диалогового окна файла. Gets or sets the file dialog box title.
(Унаследовано от FileDialog)
Возвращает или задает значение, указывающее, принимает ли диалоговое окно только допустимые имена файлов Win32. Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.
(Унаследовано от FileDialog)
Методы
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. 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 the file dialog box.
(Унаследовано от FileDialog)
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. 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)
Вызывает событие FileOk. Raises the FileOk event.
(Унаследовано от FileDialog)
Вызывает событие HelpRequest. Raises the HelpRequest event.
(Унаследовано от CommonDialog)
Открывает выбранный пользователем файл в режиме «только чтение». Opens the file selected by the user, with read-only permission. Файл задается свойством FileName. The file is specified by the FileName property.
Определяет процедуру окна-владельца, которая переопределяется, чтобы добавить специальные функции для общего диалогового окна. Defines the owner window procedure that is overridden to add specific functionality to a common dialog box.
(Унаследовано от CommonDialog)
Восстанавливает заданные по умолчанию значения всех свойств. Resets all properties to their default values.
Указывает общее диалоговое окно. Specifies a common dialog box.
(Унаследовано от FileDialog)
Запускает общее диалоговое окно с заданным по умолчанию владельцем. Runs a common dialog box with a default owner.
(Унаследовано от CommonDialog)
Запускает общее диалоговое окно с указанным владельцем. Runs a common dialog box with the specified owner.
(Унаследовано от CommonDialog)
Представляет строковую версию этого объекта. Provides a string version of this object.
(Унаследовано от FileDialog)
События
Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.
(Унаследовано от Component)
Происходит при нажатии пользователем кнопки Открыть или Сохранить в диалоговом окне файла. Occurs when the user clicks on the Open or Save button on a file dialog box.
(Унаследовано от FileDialog)
Происходит при нажатии пользователем кнопки справки в общем диалоговом окне. Occurs when the user clicks the Help button on a common dialog box.