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.
Common Dialog. Show Dialog Метод
Определение
Запускает общее диалоговое окно. Runs a common dialog box.
Перегрузки
Запускает общее диалоговое окно с заданным по умолчанию владельцем. Runs a common dialog box with a default owner.
Запускает общее диалоговое окно с указанным владельцем. Runs a common dialog box with the specified owner.
ShowDialog()
Запускает общее диалоговое окно с заданным по умолчанию владельцем. Runs a common dialog box with a default owner.
Возвращаемое значение
Объект OK, если пользователь нажимает кнопку ОК в диалоговом окне; в противном случае — объект Cancel. OK if the user clicks OK in the dialog box; otherwise, Cancel.
Примеры
В следующем примере кода используется ColorDialog реализация CommonDialog и демонстрируется создание и отображение диалогового окна. The following code example uses the ColorDialog implementation of CommonDialog and illustrates creating and showing a dialog box. В этом примере требуется, чтобы метод вызывался из существующей формы, которая имеет TextBox и Button поместила в нее. This example requires that the method is called from within an existing form, which has a TextBox and Button placed on it.
Комментарии
Этот метод реализует RunDialog. This method implements RunDialog.
См. также раздел
ShowDialog(IWin32Window)
Запускает общее диалоговое окно с указанным владельцем. Runs a common dialog box with the specified owner.
Параметры
Любой объект, который реализует IWin32Window, представляющий окно верхнего уровня, которое станет владельцем модального диалогового окна. Any object that implements IWin32Window that represents the top-level window that will own the modal dialog box.
Возвращаемое значение
Значение OK, если пользователь нажимает кнопку ОК в диалоговом окне; в противном случае значение Cancel. OK if the user clicks OK in the dialog box; otherwise, Cancel.
Комментарии
Эта версия ShowDialog метода позволяет указать конкретную форму или элемент управления, который будет владеть отображаемым диалоговым окном. This version of the ShowDialog method allows you to specify a specific form or control that will own the dialog box that is shown. Если вы используете версию этого метода без параметров, отображаемое диалоговое окно будет автоматически владельцем текущего активного окна приложения. If you use the version of this method that has no parameters, the dialog box being shown would be owned automatically by the currently active window of your application.
Создание модальных диалоговых окон и управление ими Create and manage modal dialog boxes
При создании модального диалогового окна в Visual Studio необходимо убедиться, что родительское окно диалогового окна отключено во время отображения диалогового окна, а затем снова включить родительское окно после закрытия диалогового окна. When you create a modal dialog box inside Visual Studio, you must make sure that the parent window of the dialog box is disabled while the dialog box is displayed, then re-enable the parent window after the dialog box is closed. Если этого не сделать, может появиться сообщение об ошибке: Microsoft Visual Studio не может завершить работу, так как открыто модальное диалоговое окно. Закройте активное диалоговое окно и повторите попытку. If you do not do so, you may receive the error: Microsoft Visual Studio cannot shut down because a modal dialog is active. Close the active dialog and try again.
Это делается двумя способами. There are two ways of doing this. Рекомендуемый способ, если имеется диалоговое окно WPF, является производным от DialogWindow , а затем вызывается ShowModal для вывода диалогового окна. The recommended way, if you have a WPF dialog box, is to derive it from DialogWindow, and then call ShowModal to display the dialog box. В этом случае нет необходимости управлять модальным состоянием родительского окна. If you do this, you do not need to manage the modal state of the parent window.
Если диалоговое окно не является WPF или по какой-либо другой причине не удается создать класс диалогового окна из DialogWindow , необходимо получить родительский элемент диалогового окна, вызвав GetDialogOwnerHwnd метод и самостоятельно управлять модальным состоянием. для этого EnableModeless перед отображением диалогового окна вызовите его с параметром 0 (false) и снова вызовите метод с параметром 1 (true) после закрытия диалогового окна. If your dialog box is not WPF, or for some other reason you cannot derive your dialog box class from DialogWindow, then you must get the parent of the dialog box by calling GetDialogOwnerHwnd and manage the modal state yourself, by calling the EnableModeless method with a parameter of 0 (false) before displaying the dialog box and calling the method again with a parameter of 1 (true) after closing the dialog box.
Создание диалогового окна, производного от Диалогвиндов Create a dialog box derived from DialogWindow
Создайте проект VSIX с именем опендиалогтест и добавьте команду меню с именем опендиалог. Create a VSIX project named OpenDialogTest and add a menu command named OpenDialog. Дополнительные сведения о том, как это сделать, см. в разделе Создание расширения с помощью команды меню. For more information about how to do this, see Create an extension with a menu command.
Чтобы использовать DialogWindow класс, необходимо добавить ссылки на следующие сборки (на вкладке «платформа» диалогового окна » Добавление ссылки «): To use the DialogWindow class, you must add references to the following assemblies (in the Framework tab of the Add Reference dialog box):
В OpenDialog.CSдобавьте следующую using инструкцию: In OpenDialog.cs, add the following using statement:
Объявите класс с именем TestDialogWindow , производным от DialogWindow : Declare a class named TestDialogWindow that derives from DialogWindow:
Чтобы можно было максимально увеличить и развернуть диалоговое окно, задайте HasMaximizeButton для параметра и значение HasMinimizeButton true: To be able to minimize and maximize the dialog box, set HasMaximizeButton and HasMinimizeButton to true:
В OpenDialog.ShowMessageBox методе замените существующий код следующим: In the OpenDialog.ShowMessageBox method, replace the existing code with the following:
Выполните сборку и запустите приложение. Build and run the application. Должен отобразиться экспериментальный экземпляр Visual Studio. The experimental instance of Visual Studio should appear. В меню Сервис экспериментального экземпляра должна отобразиться команда с именем Invoke опендиалог. On the Tools menu of the experimental instance you should see a command named Invoke OpenDialog. При нажатии этой команды должно отобразиться диалоговое окно. When you click this command, you should see the dialog window. Вы сможете максимально увеличить и развернуть окно. You should be able to minimize and maximize the window.
Создание и управление диалоговым окном, не производным от Диалогвиндов Create and manage a dialog box not derived from DialogWindow
Для этой процедуры можно использовать решение опендиалогтест , созданное в предыдущей процедуре, с теми же ссылками на сборки. For this procedure, you can use the OpenDialogTest solution you created in the previous procedure, with the same assembly references.
Добавьте следующие using объявления: Add the following using declarations:
Создайте класс с именем TestDialogWindow2 , производным от Window : Create a class named TestDialogWindow2 that derives from Window:
Добавьте закрытую ссылку на IVsUIShell : Add a private reference to IVsUIShell:
Добавьте конструктор, который задает ссылку на IVsUIShell : Add a constructor that sets the reference to IVsUIShell:
В OpenDialog.ShowMessageBox методе замените существующий код следующим: In the OpenDialog.ShowMessageBox method, replace the existing code with the following:
Выполните сборку и запустите приложение. Build and run the application. В меню Сервис должна отобразиться команда с именем Invoke опендиалог. On the Tools menu you should see a command named Invoke OpenDialog. При нажатии этой команды должно отобразиться диалоговое окно. When you click this command, you should see the dialog window.