Диалоговое окно windows form

Практическое руководство. Отображение диалоговых окон для Windows Forms How to: Display Dialog Boxes for Windows Forms

Диалоговое окно отображается таким же образом, как и любая другая форма в приложении. You display a dialog box in the same way you display any other form in an application. Начальная форма загружается автоматически при запуске приложения. The startup form loads automatically when the application is run. Чтобы в приложении отображалась Вторая форма или диалоговое окно, напишите код для загрузки и отображения. To make a second form or dialog box appear in the application, write code to load and display it. Аналогично, чтобы сделать форму или диалоговое окно видимым, напишите код для выгрузки или скрытия. Similarly, to make the form or dialog box disappear, write code to unload or hide it.

Отображение диалогового окна To display a dialog box

Перейдите к обработчику событий, с помощью которого необходимо открыть диалоговое окно. Navigate to the event handler with which you want to open the dialog box. Это может произойти при выборе команды меню, при нажатии кнопки или при возникновении любого другого события. This can happen when a menu command is selected, when a button is clicked, or when any other event occurs.

В обработчике событий добавьте код, чтобы открыть диалоговое окно. In the event handler, add code to open the dialog box. В этом примере для отображения диалогового окна используется событие нажатия кнопки. In this example, a button-click event is used to show the dialog box:

Элементы управления и компоненты диалоговых окон (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.

Диалоговые окна в 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.

Читайте также:  Mac os анимация launchpad

Общие сведения о компоненте 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.

Диалоговые окна в 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

Элементы управления и компоненты диалоговых окон 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.

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.

Читайте также:  Звук для windows прощание

Комментарии

Этот метод можно использовать для вывода модального диалогового окна в приложении. 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.

Шаг 7. Добавление компонентов диалогового окна в форму Step 7: Add dialog components to your form

Чтобы приложение могло открывать графические файлы и изменять цвет фона, в этом шаге следует добавить в форму компоненты OpenFileDialog и ColorDialog. To enable your app to open picture files and choose a background color, in this step, you add an OpenFileDialog component and a ColorDialog component to your form.

В некотором смысле компонент похож на элемент управления. A component is like a control in some ways. Для добавления компонента в форму используется панель элементов, его свойства настраиваются в окне Свойства. You use the Toolbox to add a component to your form, and you set its properties using the Properties window. Но в отличие от элемента управления, добавление в форму компонента не добавляет в форму элемент, который может видеть пользователь. But unlike a control, adding a component to your form doesn’t add a visible item that the user can see on the form. Вместо этого, компонент предоставляет определенное поведение, которое можно включать в коде. Instead, it provides certain behaviors that you can trigger with code. Это компонент, который открывает диалоговое окно Открыть файл. It’s a component that opens an Open File dialog box.

Читайте также:  Turning off the windows key

Добавление компонентов диалогового окна в форму To add dialog components to your form

Выберите конструктор Windows Forms (Form1.cs [Design]) и откройте группу Диалоговые окна на панели элементов. Choose the Windows Forms Designer (Form1.cs [Design]), and then open the Dialogs group in the Toolbox.

Группа Диалоговые окна на панели элементов содержит компоненты, которые открывают множество полезных диалоговых окон. Эти диалоговые окна можно использовать для открытия и сохранения файлов, просмотра папок, выбора шрифтов и цветов. The Dialogs group in the Toolbox has components that open many useful dialog boxes for you, which can be used for opening and saving files, browsing folders, and choosing fonts and colors. В этом проекте используется два компонента диалоговых окон — OpenFileDialog и ColorDialog. You use two dialog components in this project: OpenFileDialog and ColorDialog.

Чтобы добавить в форму компонент с именем openFileDialog1, дважды щелкните элемент OpenFileDialog. To add a component called openFileDialog1 to your form, double-click OpenFileDialog. Чтобы добавить в форму компонент с именем colorDialog1, дважды щелкните на панели элементов элемент ColorDialog. To add a component called colorDialog1 to your form, double-click ColorDialog in the Toolbox. (такой компонент используется в следующем шаге руководства). В нижней части конструктора Windows Forms должно быть поле (под формой программы просмотра изображений), которое содержит значок для каждого из двух добавленных компонентов диалоговых окон, как показано на рисунке ниже. (You use that one in the next tutorial step.) You should see an area at the bottom of Windows Forms Designer (beneath the Picture Viewer form) that has an icon for each of the two dialog components that you added, as shown in the following image.


Компоненты _ _диалоговых окон Dialog _ _components

Выберите значок openFileDialog1 в области в нижней части конструктора Windows Forms. Choose the openFileDialog1 icon in the area at the bottom of the Windows Forms Designer. Установите значения двух свойств. Set two properties:

Задайте для свойства Filter следующее значение (можно копировать и вставить): Set the Filter property to the following (you can copy and paste it):

Установите для свойства Title значение Выбор файла изображения. Set the Title property to the following: Select a picture file

Параметры свойства Filter определяют типы файлов, которые отображаются в диалоговом окне Выбор файла изображения. The Filter property settings specify the kinds of file types that will display in the Select a picture file dialog box.

Чтобы посмотреть пример диалогового окна Открыть файл в другом приложении, откройте программу Блокнот или Paint и выберите Файл > Открыть. To see an example of the Open File dialog box in a different application, open Notepad or Paint, and on the menu bar, choose File > Open. Обратите внимание на раскрывающийся список рядом с именем файла, в котором можно выбрать тип файла. Notice how there’s a drop-down list next to the file name that lets you choose the file type.

Вы только что настроили свойство Filter компонента OpenFileDialog в приложении. You just used the Filter property in the OpenFileDialog component to set that up in your app. Обратите внимание и на то, как выделены полужирным шрифтом свойства Title и Filter в окне Свойства. Also, notice how the Title and Filter properties are bold in the Properties window. Таким образом интегрированная среда разработки показывает свойства, у которых были изменены их значения по умолчанию. The IDE does that to show you any properties that have been changed from their default values.

Оцените статью