System windows forms keypresseventargs

Key Event Args Класс

Определение

Предоставляет данные для события KeyDown или KeyUp. Provides data for the KeyDown or KeyUp event.

Примеры

В следующих примерах кода показано, как определить состояние нажатия клавиши. The following code examples demonstrate how to detect the state of a key press.

Пример 1 Example 1

В следующем примере кода показано, как использовать KeyDown событие с Help классом для отображения всплывающего стиля справки для пользователя приложения. The following code example demonstrates how to use the KeyDown event with the Help class to display pop-up style Help to the user of the application. В примере используются KeyEventArgs свойства, передаваемые в метод обработчика событий для фильтрации всех вариантов нажатия клавиши F1 с помощью клавиши-модификатора. The example uses the KeyEventArgs properties passed to the event handler method to filter for all variations of pressing the F1 key with a modifier key. Когда пользователь нажимает любой вариант F1, включающий любой модификатор клавиатуры, Help класс отображает всплывающее окно, аналогичное ToolTip элементу управления рядом с элементом. When the user presses any variation of F1 that includes any keyboard modifier, the Help class displays a pop-up window, similar to a ToolTip, near the control. Если пользователь нажимает ALT + F2, отображается другое всплывающее окно справки с дополнительными сведениями. If the user presses ALT+F2, a different Help pop-up is displayed with additional information.

Пример 2 Example 2

В следующем примере определяется, нажал ли пользователь ALT + E, и если указатель мыши находится над TreeNode , пользователь может изменить его TreeNode . The following example determines whether the user pressed ALT+E, and if the mouse pointer is over a TreeNode, allows the user to edit that TreeNode.

Пример 3 Example 3

В следующем примере определяется, нажал ли пользователь нечисловой ключ, и, если да, отменяет KeyPress событие с помощью Handled Свойства. The following example determines whether the user pressed a non-numeric key, and if so, cancels the KeyPress event by using the Handled property.

Комментарии

Объект KeyEventArgs , указывающий клавишу, которую пользователь нажал и какие клавиши-модификаторы (Ctrl, Alt и Shift) были нажаты одновременно, передается с каждым KeyDown KeyUp событием или. A KeyEventArgs, which specifies the key the user pressed and whether any modifier keys (CTRL, ALT, and SHIFT) were pressed at the same time, is passed with each KeyDown or KeyUp event.

Это KeyDown событие возникает при нажатии пользователем любого ключа. The KeyDown event occurs when the user presses any key. Это KeyUp событие возникает, когда пользователь отпускает ключ. The KeyUp event occurs when the user releases the key. Повторяющиеся KeyDown события происходят при каждом повторении ключа, если ключ удерживается, но KeyUp при освобождении ключа создается только одно событие. Duplicate KeyDown events occur each time the key repeats, if the key is held down, but only one KeyUp event is generated when the user releases the key.

Это KeyPress событие также возникает при нажатии клавиши. The KeyPress event also occurs when a key is pressed. Объект KeyPressEventArgs передается с каждым KeyPress событием и указывает символ, состоящий из результатов каждого нажатия клавиши. A KeyPressEventArgs is passed with each KeyPress event, and specifies the character that was composed as a result of each key press.

Дополнительные сведения о модели событий см. в разделе обработка и вызов событий. For information about the event model, see Handling and Raising Events.

Конструкторы

Инициализирует новый экземпляр класса KeyEventArgs. Initializes a new instance of the KeyEventArgs class.

Свойства

Возвращает значение, указывающее, была ли нажата клавиша ALT. Gets a value indicating whether the ALT key was pressed.

Читайте также:  Astra linux вход неудачен домен

Возвращает значение, указывающее, была ли нажата клавиша CTRL. Gets a value indicating whether the CTRL key was pressed.

Возвращает или задает значение, указывающее, было ли обработано событие. Gets or sets a value indicating whether the event was handled.

Получает код клавиатуры для события KeyDown или события KeyUp. Gets the keyboard code for a KeyDown or KeyUp event.

Получает данные, касающиеся клавиши, для события KeyDown или KeyUp. Gets the key data for a KeyDown or KeyUp event.

Получает значение клавиатуры для события KeyDown или KeyUp. Gets the keyboard value for a KeyDown or KeyUp event.

Получает флаги модификаторов для события KeyDown или события KeyUp. Gets the modifier flags for a KeyDown or KeyUp event. Флаги указывают, какая комбинация клавиш CTRL, SHIFT и ALT была нажата. The flags indicate which combination of CTRL, SHIFT, and ALT keys was pressed.

Возвращает значение, указывающее, была ли нажата клавиша SHIFT. Gets a value indicating whether the SHIFT key was pressed.

Возвращает или задает значение, указывающее, следует ли передавать события нажатия клавиши базовому элементу управления. Gets or sets a value indicating whether the key event should be passed on to the underlying control.

Методы

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetHashCode()

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) ToString()

Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.

Key Press Event Args Класс

Определение

Предоставляет данные для события KeyPress. Provides data for the KeyPress event.

Примеры

В следующем примере показано использование параметра KeyPressEventArgs для подсчета ключей при их нажатии и отображение результатов после каждого нажатия клавиши. The following example illustrates using the KeyPressEventArgs to count keys as they are pressed and to display the results after each key press. Handled затем принимает значение true, чтобы операционная система не продолжала обрабатывать ключ. Handled is then set to true to keep the operating system from further processing the key. В примере предполагается наличие формы с TextBox помещенным на нее. The example assumes a form with a TextBox placed on it.

Необходимо создать новый экземпляр этого класса. You must create a new instance of this class. Необходимо также задать обработчик событий. You must also set the event handler. Это можно сделать в конструкторе для класса. You can do this in the constructor for your class.

При возникновении указанного события в элементе управления вызывается присоединенный метод, и приложение может выполнить код в ответ на событие. When the specified event is raised in the control, the attached method is called and the application can execute code in response to the event.

Комментарии

KeyPressEventArgsУказывает символ, который формируется, когда пользователь нажимает клавишу. A KeyPressEventArgs specifies the character that is composed when the user presses a key. Например, когда пользователь нажимает SHIFT + K, KeyChar свойство возвращает прописную букву k. For example, when the user presses SHIFT + K, the KeyChar property returns an uppercase K.

KeyPressСобытие возникает, когда пользователь нажимает клавишу. A KeyPress event occurs when the user presses a key. Два события, тесно связанных с KeyPress событием, — это KeyUp и KeyDown . Two events that are closely related to the KeyPress event are KeyUp and KeyDown. KeyDownСобытие предшествует каждому KeyPress событию, когда пользователь нажимает клавишу, и KeyUp событие возникает, когда пользователь отпускает ключ. The KeyDown event precedes each KeyPress event when the user presses a key, and a KeyUp event occurs when the user releases a key. Когда пользователь удерживает ключ, повторяющиеся KeyDown KeyPress события и возникают каждый раз при повторении символа. When the user holds down a key, duplicate KeyDown and KeyPress events occur each time the character repeats. KeyUpПри выпуске создается одно событие. One KeyUp event is generated upon release.

Читайте также:  Igo карты для навигатора windows ce

При каждом KeyPress событии KeyPressEventArgs передается значение. With each KeyPress event, a KeyPressEventArgs is passed. KeyEventArgsПередается с каждым KeyDown KeyUp событием и. A KeyEventArgs is passed with each KeyDown and KeyUp event. KeyEventArgsУказывает, были ли нажаты все клавиши-модификаторы (Ctrl, Shift или Alt) вместе с другим ключом. A KeyEventArgs specifies whether any modifier keys (CTRL, SHIFT, or ALT) were pressed along with another key. (Эти сведения об модификаторе также можно получить с помощью ModifierKeys свойства Control класса.) (This modifier information can also be obtained through the ModifierKeys property of the Control class.)

Задайте Handled для значение, true чтобы отменить KeyPress событие. Set Handled to true to cancel the KeyPress event. Это позволяет элементу управления обрабатывать нажатие клавиши. This keeps the control from processing the key press.

Некоторые элементы управления обрабатывают определенные клавиши KeyDown . Some controls will process certain key strokes on KeyDown. Например, RichTextBox обрабатывает клавишу ВВОД перед KeyPress вызовом метода. For example, RichTextBox processes the Enter key before KeyPress is called. В таких случаях нельзя отменить KeyPress событие, а KeyDown вместо этого отменить его. In such cases, you cannot cancel the KeyPress event, and must cancel the key stroke from KeyDown instead.

Дополнительные сведения о модели событий см. в разделе обработка и вызов событий. For information about the event model, see Handling and Raising Events.

Конструкторы

Инициализирует новый экземпляр класса KeyPressEventArgs. Initializes a new instance of the KeyPressEventArgs class.

Свойства

Возвращает или задает значение, показывающее, было ли обработано событие KeyPress. Gets or sets a value indicating whether the KeyPress event was handled.

Возвращает или задает символ, соответствующий нажатой клавише. Gets or sets the character corresponding to the key pressed.

Методы

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetHashCode()

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) ToString()

Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.

Key Press Event Args. Key Char Свойство

Определение

Возвращает или задает символ, соответствующий нажатой клавише. Gets or sets the character corresponding to the key pressed.

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

Получаемый знак ASCII. The ASCII character that is composed. Например, при нажатии клавиш SHIFT + K данное свойство возвращает прописной знак K. For example, if the user presses SHIFT + K, this property returns an uppercase K.

Примеры

В следующем примере создается TextBox элемент управления. The following example creates a TextBox control. keypressed Метод использует свойство, KeyChar чтобы проверить, нажата ли клавиша ВВОД. The keypressed method uses the KeyChar property to check whether the ENTER key pressed. Если нажата клавиша ВВОД, Handled свойство имеет значение true , которое указывает, что событие обрабатывается. If the ENTER key is pressed, the Handled property is set to true , which indicates the event is handled.

Комментарии

Используйте KeyChar свойство, чтобы выполнить выборку нажатий клавиш во время выполнения и изменить нажатия клавиш в особых обстоятельствах времени выполнения. Use the KeyChar property to sample keystrokes at run time and to modify keystrokes under special run-time circumstances. Например, можно использовать KeyChar для отключения нечисловых сочетаний клавиш, когда пользователь вводит почтовый индекс, изменяет все буквенные нажатия на прописные в поле ввода данных или наблюдайте на клавиатуре или другом устройстве ввода клавиш для конкретных сочетаний клавиш. For example, you can use KeyChar to disable non-numeric keypresses when the user enters a ZIP code, change all alphabetical keypresses to uppercase in a data entry field, or monitor the keyboard or other key input device for specific key combinations.

Читайте также:  Меню дополнительных вариантов загрузки windows выберите безопасный режим

Вы можете получить или задать следующие ключи: You can get or set the following keys:

a – z, A – Z. a-z, A-Z.

Знаки препинания. Punctuation marks.

Числовые ключи в верхней части клавиатуры и на цифровой клавиатуре. Number keys, both across the top of the keyboard and on the numeric keypad.

Невозможно получить или задать следующие ключи: You cannot get or set the following keys:

Клавиша TAB. The TAB key.

Вставка и удаление. INSERT and DELETE.

Выровнять по СТРАНИЦАм вверх и вниз. PAGE UP and PAGE DOWN.

Клавиши со стрелками Arrow keys.

Дополнительные сведения об обнаружении любых несимвольных ключей, указанных выше, см. в разделе KeyEventArgs класс. For information about how to detect any of the non-character keys mentioned above, see the KeyEventArgs class.

Key Press Event Args Class

Definition

Provides data for the KeyPress event.

Examples

The following example illustrates using the KeyPressEventArgs to count keys as they are pressed and to display the results after each key press. Handled is then set to true to keep the operating system from further processing the key. The example assumes a form with a TextBox placed on it.

You must create a new instance of this class. You must also set the event handler. You can do this in the constructor for your class.

When the specified event is raised in the control, the attached method is called and the application can execute code in response to the event.

Remarks

A KeyPressEventArgs specifies the character that is composed when the user presses a key. For example, when the user presses SHIFT + K, the KeyChar property returns an uppercase K.

A KeyPress event occurs when the user presses a key. Two events that are closely related to the KeyPress event are KeyUp and KeyDown. The KeyDown event precedes each KeyPress event when the user presses a key, and a KeyUp event occurs when the user releases a key. When the user holds down a key, duplicate KeyDown and KeyPress events occur each time the character repeats. One KeyUp event is generated upon release.

With each KeyPress event, a KeyPressEventArgs is passed. A KeyEventArgs is passed with each KeyDown and KeyUp event. A KeyEventArgs specifies whether any modifier keys (CTRL, SHIFT, or ALT) were pressed along with another key. (This modifier information can also be obtained through the ModifierKeys property of the Control class.)

Set Handled to true to cancel the KeyPress event. This keeps the control from processing the key press.

Some controls will process certain key strokes on KeyDown. For example, RichTextBox processes the Enter key before KeyPress is called. In such cases, you cannot cancel the KeyPress event, and must cancel the key stroke from KeyDown instead.

For information about the event model, see Handling and Raising Events.

Constructors

Initializes a new instance of the KeyPressEventArgs class.

Properties

Gets or sets a value indicating whether the KeyPress event was handled.

Gets or sets the character corresponding to the key pressed.

Methods

Determines whether the specified object is equal to the current object.

(Inherited from Object) GetHashCode()

Serves as the default hash function.

(Inherited from Object) GetType()

Gets the Type of the current instance.

(Inherited from Object) MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object) ToString()

Returns a string that represents the current object.

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