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.
Print Dialog Класс
Определение
Позволяет пользователям выбирать принтер и определять, какие разделы документа должны быть напечатаны из приложения Windows Forms. Lets users select a printer and choose which sections of the document to print from a Windows Forms application.
Примеры
В следующем примере кода показано, как использовать PrintDialog элемент управления для задания AllowSomePages свойств, ShowHelp и Document . The following code example demonstrates how to use the PrintDialog control to set the AllowSomePages, ShowHelp, and Document properties. Чтобы выполнить этот пример, вставьте следующий код в форму, содержащую PrintDialog элемент управления с именем PrintDialog1 и кнопку с именем Button1 . To run this example, paste the following code into a form that contains a PrintDialog control named PrintDialog1 and a button named Button1 . В этом примере требуется, Click чтобы событие кнопки и PrintPage событие были docToPrint подключены к методам обработки событий, определенным в этом примере. This example requires that the button’s Click event and the PrintPage event of docToPrint have been connected to the event-handling methods defined in this example.
Комментарии
При создании экземпляра PrintDialog свойства чтения и записи устанавливаются в начальные значения. When you create an instance of PrintDialog, the read/write properties are set to initial values. Список этих значений см. в конструкторе PrintDialog. For a list of these values, see the PrintDialog constructor. Чтобы получить параметры принтера, измененные пользователем с помощью PrintDialog , используйте PrinterSettings свойство. To get printer settings that are modified by the user with the PrintDialog, use the PrinterSettings property.
Дополнительные сведения о печати с помощью Windows Forms см. в разделе System.Drawing.Printing Общие сведения о пространстве имен. For more information about printing with Windows Forms, see the System.Drawing.Printing namespace overview. Если требуется выполнить печать из Windows Presentation Foundation приложения, см System.Printing . раздел пространство имен. If you want to print from a Windows Presentation Foundation application, see the System.Printing namespace.
Конструкторы
Инициализирует новый экземпляр класса PrintDialog. Initializes a new instance of the PrintDialog class.
Свойства
Получает или задает значение, указывающее, отображается ли переключатель Текущая страница. Gets or sets a value indicating whether the Current Page option button is displayed.
Получает или задает значение, указывающее, установлен ли флажок Печать в файл. Gets or sets a value indicating whether the Print to file check box is enabled.
Получает или задает значение, определяющее, включен ли переключатель Выбор. Gets or sets a value indicating whether the Selection option button is enabled.
Получает или задает значение, определяющее, включен ли переключатель Страницы. Gets or sets a value indicating whether the Pages option button is enabled.
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.
(Унаследовано от Component)
Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.
(Унаследовано от Component)
Получает или задает значение, указывающее, какой объект PrintDocument используется для получения PrinterSettings. Gets or sets a value indicating the PrintDocument used to obtain PrinterSettings.
Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.
(Унаследовано от Component)
Получает или задает параметры принтера, которые можно изменить в диалоговом окне. Gets or sets the printer settings the dialog box modifies.
Получает или задает значение, указывающее, установлен ли флажок Печать в файл. Gets or sets a value indicating whether the Print to file check box is selected.
Получает или задает значение, определяющее, отображается ли кнопка Справка. Gets or sets a value indicating whether the Help button is displayed.
Получает или задает значение, определяющее, отображается ли кнопка Сеть. Gets or sets a value indicating whether the Network button is displayed.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Получает или задает объект, содержащий данные элемента управления. Gets or sets an object that contains data about the control.
(Унаследовано от CommonDialog)
Возвращает или задает значение, указывающее, должно ли диалоговое окно отображаться в стиле Windows XP для систем под управлением Windows XP Home Edition, Windows XP Professional, Windows Server 2003 или более поздней версии. Gets or sets a value indicating whether the dialog should be shown in the Windows XP style for systems running Windows XP Home Edition, Windows XP Professional, Windows Server 2003 or later.
Методы
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. 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 all options, the last selected printer, and the page settings 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)
Происходит при нажатии пользователем кнопки справки в общем диалоговом окне. Occurs when the user clicks the Help button on a common dialog box.