Windows form message dialog

Form. Dialog Result Свойство

Определение

Возвращает или задает результат диалога для формы. Gets or sets the dialog result for the form.

Значение свойства

Объект DialogResult, представляющий результат формы при использовании в качестве диалогового окна. A DialogResult that represents the result of the form when used as a dialog box.

Исключения

Заданное значение находится вне диапазона допустимых значений. The value specified is outside the range of valid values.

Примеры

В следующем примере форма отображается как диалоговое окно и отображается окно сообщения, указывающее, была ли нажата кнопка ОК или Отмена в форме при обращении к DialogResult свойству формы. The following example displays a form as a dialog box and displays a message box indicating whether the OK or Cancel button of the form was clicked by referencing the DialogResult property of the form.

Комментарии

Результат в диалоговом окне формы — это значение, возвращаемое формой при его отображении в виде модального диалогового окна. The dialog result of a form is the value that is returned from the form when it is displayed as a modal dialog box. Если форма отображается как диалоговое окно, установка этого свойства со значением из DialogResult перечисления задает значение результата диалогового окна для формы, скрывает модальное диалоговое окно и возвращает управление вызывающей форме. If the form is displayed as a dialog box, setting this property with a value from the DialogResult enumeration sets the value of the dialog box result for the form, hides the modal dialog box, and returns control to the calling form. Это свойство обычно задается DialogResult свойством Button элемента управления в форме. This property is typically set by the DialogResult property of a Button control on the form. Когда пользователь щелкает Button элемент управления, значение, присвоенное DialogResult свойству объекта, Button присваивается DialogResult свойству формы. When the user clicks the Button control, the value assigned to the DialogResult property of the Button is assigned to the DialogResult property of the form.

Когда форма отображается как модальное диалоговое окно, нажатие кнопки Закрыть (кнопка с крестиком в правом верхнем углу формы) приводит к скрытию формы и свойству, для которого DialogResult устанавливается значение DialogResult.Cancel . When a form is displayed as a modal dialog box, clicking the Close button (the button with an X in the top-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel . CloseМетод не вызывается автоматически, когда пользователь нажимает кнопку « Закрыть » диалогового окна или задает значение DialogResult Свойства. The Close method is not automatically called when the user clicks the Close 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 of this behavior, you must call the Dispose method of the form when the form is no longer needed by your application.

С помощью этого свойства можно определить, как диалоговое окно закрывается для правильной обработки действий, выполняемых в диалоговом окне. You can use this property to determine how a dialog box is closed in order to properly process the actions performed in the dialog box.

Читайте также:  Не открывать браузер при запуске windows

Можно переопределить значение, присваиваемое DialogResult свойству, когда пользователь нажимает кнопку Закрыть , задавая DialogResult свойство в обработчике событий для события в Closing форме. You can override the value assigned to the DialogResult property when the user clicks the Close button by setting the DialogResult property in an event handler for the Closing event of the form.

Если объект Form отображается как немодальное окно, значение, возвращаемое DialogResult свойством, может не возвращать значение, присвоенное форме, так как ресурсы формы автоматически освобождаются при закрытии формы. If a Form is displayed as a modeless window, the value returned by the DialogResult property might not return a value assigned to the form because the form’s resources are automatically released when the form is closed.

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

Создание диалога в Windows Forms на C++

Создание приложения Windows Forms на C++/CLI в Windows 8
Добрый день! Нужно создать windows приложение на Си++, стоит 8, на 2013 много заморочек с созданием.

создание Windows Forms Aplication
такой вопросик. Мне поставлена задача, сделать программу(калькулятор) используя «Visual C++ 2005».

Создание приложения Windows Forms
Здравствуйте. В программировании ничего не понимаю, но работники нашей конторы плохо работают с.

Создание приложений Windows Forms
Добрый день. Есть такая задача: Создать приложение, выводящее на экран показания времени.

Это если привязать несколько файлов к заголовочному > добавить ->новый элемент-> класс UI -> WindowsForm ->Имя_новой_формы. Появится Имя_новой_формы.h (прямо под Form1.h) доступный к визуализации и редактированию из дизайнера\

а мне надо типа как здесь все в одном файле прописать
Double-click the new menu item to create a handler for it, and edit the code as shown below for the handler so that it displays the dialog box.

Читайте также:  Как снять защиту с диска mac os дисковая утилита

или вот еше код

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Windows.Forms — создание приложения
было задание,нужно было написать программу, которая отвечала на вопрос без помощи массивов. Теперь.

Создание объектов Windows.Forms
Вопрос к тем, кто имел опыт работы связанной с созданием объектов Windows.Forms через PowerShell .

Создание Windows Forms и его запуск
Ребят, возникла такая проблема: создаю пустой проект и добавляю новый элемент «Форма Windows.

Динамическое создание компонентов в Windows Forms
Доброго времени суток! Пилю курсовую,возникла проблема с динамическим созданием компонентов в VS.

Prompt Dialog in Windows Forms

I am using System.Windows.Forms but strangely enough don’t have the ability to create them.

How can I get something like a javascript prompt dialog, without javascript?

MessageBox is nice, but there is no way for the user to enter an input.

I want the user to enter any text input possible.

11 Answers 11

You need to create your own Prompt dialog. You could perhaps create a class for this.

Update:

Added default button (enter key) and initial focus based on comments and another question.

Add reference to Microsoft.VisualBasic and use this into your C# code:

To add the refernce: right-click on the References in your Project Explorer window then on Add Reference, and check VisualBasic from that list.

There is no such thing natively in Windows Forms.

You have to create your own form for that or:

use the Microsoft.VisualBasic reference.

Inputbox is legacy code brought into .Net for VB6 compatibility — so i advise to not do this.

It’s generally not a real good idea to import the VisualBasic libraries into C# programs (not because they won’t work, but just for compatibility, style, and ability to upgrade), but you can call Microsoft.VisualBasic.Interaction.InputBox() to display the kind of box you’re looking for.

If you can create a Windows.Forms object, that would be best, but you say you cannot do that.

The answer of Bas can get you in memorytrouble theoretically, since ShowDialog won’t be disposed. I think this is a more proper way. Also mention the textLabel being readable with longer text.

Other way of doing this: Assuming that you have a TextBox input type, Create a Form, and have the textbox value as a public property.

In the main form, this will be the code:

This way, the code looks cleaner:

  1. If validation logic is added.
  2. If various other input types are added.

Based on the work of Bas Brekelmans above, I have also created two derivations -> «input» dialogs that allow you to receive from the user both a text value and a boolean (TextBox and CheckBox):

. and text along with a selection of one of multiple options (TextBox and ComboBox):

Both require the same usings:

Call them like so:

Call them like so:

Bas Brekelmans’s answer is very elegant in its simplicity. But, I found that for an actual application a little more is needed such as:

  • Grow form appropriately when message text is too long.
  • Doesn’t automatically popup in middle of screen.
  • Doesn’t provide any validation of user input.

I just downloaded source and copied InputBox.cs into my project.

Surprised there isn’t something even better though. My only real complaint is it caption text doesn’t support newlines in it since it uses a label control.

Unfortunately C# still doesn’t offer this capability in the built in libs. The best solution at present is to create a custom class with a method that pops up a small form. If you’re working in Visual Studio you can do this by clicking on Project >Add class

Читайте также:  Как создать загрузочный flash для mac os

Visual C# items >code >class

Name the class PopUpBox (you can rename it later if you like) and paste in the following code:

You will need to change the namespace to whatever you’re using. The method returns a string, so here’s an example of how to implement it in your calling method:

This method checks the returned string for a text value, empty string, or «cancel» (the getUserInput method returns «cancel» if the cancel button is clicked) and acts accordingly. If the user didn’t enter anything and clicked OK it will tell the user and ask them if they want to cancel or re-enter their text.

Post notes: In my own implementation I found that all of the other answers were missing 1 or more of the following:

  • A cancel button
  • The ability to contain symbols in the string sent to the method
  • How to access the method and handle the returned value.

Thus, I have posted my own solution. I hope someone finds it useful. Credit to Bas and Gideon + commenters for your contributions, you helped me to come up with a workable solution!

Form. Dialog Result Property

Definition

Gets or sets the dialog result for the form.

Property Value

A DialogResult that represents the result of the form when used as a dialog box.

Exceptions

The value specified is outside the range of valid values.

Examples

The following example displays a form as a dialog box and displays a message box indicating whether the OK or Cancel button of the form was clicked by referencing the DialogResult property of the form.

Remarks

The dialog result of a form is the value that is returned from the form when it is displayed as a modal dialog box. If the form is displayed as a dialog box, setting this property with a value from the DialogResult enumeration sets the value of the dialog box result for the form, hides the modal dialog box, and returns control to the calling form. This property is typically set by the DialogResult property of a Button control on the form. When the user clicks the Button control, the value assigned to the DialogResult property of the Button is assigned to the DialogResult property of the form.

When a form is displayed as a modal dialog box, clicking the Close button (the button with an X in the top-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel . The Close method is not automatically called when the user clicks the Close 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 of this behavior, you must call the Dispose method of the form when the form is no longer needed by your application.

You can use this property to determine how a dialog box is closed in order to properly process the actions performed in the dialog box.

You can override the value assigned to the DialogResult property when the user clicks the Close button by setting the DialogResult property in an event handler for the Closing event of the form.

If a Form is displayed as a modeless window, the value returned by the DialogResult property might not return a value assigned to the form because the form’s resources are automatically released when the form is closed.

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