- Ввод данных пользователем в Windows Forms User Input in Windows Forms
- в этом разделе In This Section
- Form. Show Dialog Метод
- Определение
- Перегрузки
- ShowDialog()
- Возвращаемое значение
- Исключения
- Примеры
- Комментарии
- Диалоговые окна в Windows Forms Dialog Boxes in Windows Forms
- в этом разделе In This Section
- Связанные разделы Related Sections
- Input Dialog Class
- Definition
- Constructors
- Fields
- Properties
- Methods
- Extension Methods
- Prompt Dialog in Windows Forms
- 11 Answers 11
Ввод данных пользователем в Windows Forms User Input in Windows Forms
В Windows Forms включена модель ввода пользователя, основанная на событиях, которые возникают во время обработки соответствующих сообщений Windows. Windows Forms includes a user input model based on events that are raised while processing related Windows messages. Здесь приведены ссылки на разделы с информацией о вводе с помощью мыши и клавиатуры, включая примеры кода, демонстрирующие выполнение определенных задач. The topics in this section provide information on mouse and keyboard user input, including code examples that demonstrate how to perform specific tasks.
в этом разделе In This Section
Ввод данных пользователем в приложении Windows Forms User Input in a Windows Forms Application
Содержит обзор событий пользовательского ввода и методов, которые обрабатывают сообщения Windows. Provides an overview of user input events and the methods that process Windows messages.
Ввод с клавиатуры в приложении Windows Forms Keyboard Input in a Windows Forms Application
Содержит сведения об обработке сообщений клавиатуры, различных типах клавиш и событиях клавиатуры. Provides information on keyboard message handling, the different types of keys, and the keyboard events.
Ввод данных мышью в приложении Windows Forms Mouse Input in a Windows Forms Application
Содержит сведения о событиях мыши и других связанных с мышью возможностях, включая курсоры и отслеживание перемещения мыши. Provides information on the mouse events and other mouse-related features, including mouse cursors and mouse capture.
Практическое руководство. Имитация событий мыши и клавиатуры в коде How to: Simulate Mouse and Keyboard Events in Code
Показано несколько различных способов программной имитации ввода с помощью мыши и клавиатуры. Demonstrates several different ways to programmatically simulate mouse and keyboard input.
Практическое руководство. Обработка событий пользовательского ввода в элементах управления Windows Forms How to: Handle User Input Events in Windows Forms Controls
Пример кода, который обрабатывает большую часть событий пользовательского ввода и сообщает сведения о каждом событии. Presents a code example that handles most user input events and reports information about each event.
Проверка введенных пользователем данных в Windows Forms User Input Validation in Windows Forms
Описываются методы проверки пользовательского ввода в приложениях Windows Forms. Describes the methods to validate user input in Windows Forms applications.
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.
Диалоговые окна в 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.
Input Dialog Class
Definition
Defines input dialogs.
Constructors
Fields
Defines dialog context turn count property value.
Defines dialog context state property value.
Properties
Gets or sets intteruption policy.
Gets or sets a value indicating whether the input should always prompt the user regardless of there being a value or not.
Gets or sets the default value for the input dialog when MaxTurnCount is exceeded.
Gets or sets the activity template to send when MaxTurnCount has been reached and the default value is used.
Gets or sets whether this action should be disabled.
Gets or sets id for the dialog.
(Inherited from Dialog)
Gets or sets the activity template to send to the user whenever the value provided is invalid.
Gets or sets maximum number of times to ask the user for this value before the dialog gives up.
Gets or sets the activity to send to the user.
Gets or sets the memory property path which the value will be bound to.
Gets the information of the cref=»SourceRange»/>.
(Inherited from Dialog)
Gets or sets the IBotTelemetryClient to use for logging.
(Inherited from Dialog)
Gets or sets the activity template for retrying.
Gets or sets the expressions to run to validate the input.
Gets or sets a the expression to use to bind input to the dialog.
Methods
AppendChoices is utility method to build up a message activity given all of the options.
Called when the dialog is started and pushed onto the dialog stack.
Called when the dialog is continued, where it is the active dialog and the user replies with a new activity.
Called when the dialog is ending.
(Inherited from Dialog)
Gets a unique string which represents the version of this dialog. If the version changes between turns the dialog system will emit a DialogChanged event.
(Inherited from Dialog)
Builds the compute Id for the dialog.
(Inherited from Dialog)
Called when an event has been raised, using DialogContext.emitEvent() , by either the current dialog or a dialog that the current dialog started.
(Inherited from Dialog)
Method which processes options.
Called after an event was bubbled to all parents and wasn’t handled.
(Inherited from Dialog)
Called before an event is bubbled to its parent.
Called when input has been received, override this method to customize recognition of the input.
Method which renders the prompt to the user give n the current input state.
Registers a cref=»SourceRange»/> in the provided location.
(Inherited from Dialog)
Called when the dialog should re-prompt the user for input.
(Inherited from Dialog)
Called when a child dialog completes its turn, returning control to this dialog.
Extension Methods
Creates a dialog stack and starts a dialog, pushing it onto the stack.
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:
- If validation logic is added.
- 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
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!