System windows forms keys control

Control. Is Input Key(Keys) Метод

Определение

Определяет, является ли заданная клавиша обычной клавишей ввода или специальной клавишей, нуждающейся в предварительной обработке. Determines whether the specified key is a regular input key or a special key that requires preprocessing.

Параметры

Одно из значений перечисления Keys. One of the Keys values.

Возвращаемое значение

Значение true , если указанная клавиша является стандартной клавишей ввода; в противном случае — значение false . true if the specified key is a regular input key; otherwise, false .

Примеры

В следующем примере кода показано, как переопределить IsInputKey метод для TextBox элемента управления. The following code example shows you how to override the IsInputKey method for a TextBox control. В этом примере TabTextBox класс обрабатывает клавишу TAB. In this example, the TabTextBox class handles the TAB key. Когда TabTextBox фокус переключается и пользователь нажимает клавишу TAB, в точку вставки текста добавляется четыре пробела, заменяя любой выделенный текст. When the TabTextBox has the focus and the user presses the TAB key four spaces are added at the text insertion point, replacing any selected text. По умолчанию TextBox элемент управления обрабатывает клавишу TAB, перемещая фокус ввода на следующий элемент управления. By default, the TextBox control handles the TAB key by moving the input focus to the next control. В этом случае нажатие клавиши никогда не достигает OnKeyDown переопределения метода. In this case, the keypress never reaches the OnKeyDown method override. Чтобы предотвратить это поведение по умолчанию, IsInputKey Переопределение метода возвращает, true когда пользователь нажимает клавишу TAB. To prevent this default behavior, the IsInputKey method override returns true when the user presses the TAB key. Для всех других нажатий клавиш IsInputKey Переопределение метода возвращает результат вызова версии базового класса метода. For all other keypresses, the IsInputKey method override returns the result of calling the base-class version of the method.

Комментарии

Вызовите IsInputKey метод, чтобы определить, является ли ключ, заданный keyData параметром, ключом ввода, который требуется элементу управления. Call the IsInputKey method to determine whether the key specified by the keyData parameter is an input key that the control wants. Этот метод вызывается во время предварительной обработки сообщения окна, чтобы определить, следует ли предварительно обработать указанный входной ключ или отправить его непосредственно в элемент управления. This method is called during window message preprocessing to determine whether the specified input key should be preprocessed or sent directly to the control. Если IsInputKey возвращает true , указанный ключ отправляется непосредственно в элемент управления. If IsInputKey returns true , the specified key is sent directly to the control. Если IsInputKey возвращает false , указанный ключ предварительно обрабатывается и отправляется в элемент управления только в том случае, если он не занят этапом предварительной обработки. If IsInputKey returns false , the specified key is preprocessed and only sent to the control if it is not consumed by the preprocessing phase. К предварительно обработанным ключам относятся TAB, RETURN, ESC и стрелка вверх, стрелка вниз, стрелка влево и клавиши со СТРЕЛКАми вправо. Keys that are preprocessed include the TAB, RETURN, ESC, and the UP ARROW, DOWN ARROW, LEFT ARROW, and RIGHT ARROW keys.

Control. Process Cmd Key(Message, Keys) Метод

Определение

Обрабатывает клавишу для команд. Processes a command key.

Параметры

Передаваемый по ссылке объект Message, который представляет сообщение окна для обработки. A Message, passed by reference, that represents the window message to process.

Одно из значений Keys, представляющее обрабатываемую клавишу. One of the Keys values that represents the key to process.

Возвращаемое значение

Значение true , если знак был обработан элементом управления; в противном случае — значение false . true if the character was processed by the control; otherwise, false .

Читайте также:  Установка windows флешки не продолжается

Комментарии

Этот метод вызывается во время предварительной обработки сообщения для обработки ключей команд. This method is called during message preprocessing to handle command keys. Ключи команд — это ключи, которые всегда имеют приоритет над обычными входными ключами. Command keys are keys that always take precedence over regular input keys. Примеры клавиш команд: сочетания клавиш и ярлыки меню. Examples of command keys include accelerators and menu shortcuts. Метод должен возвращать true значение, указывающее, что он обработал клавишу Command, или false указывает, что ключ не является клавишей команды. The method must return true to indicate that it has processed the command key, or false to indicate that the key is not a command key. Этот метод вызывается только при размещении элемента управления в Windows Forms приложении или в качестве элемента управления ActiveX. This method is only called when the control is hosted in a Windows Forms application or as an ActiveX control.

ProcessCmdKeyМетод сначала определяет, имеет ли элемент управления ContextMenu , и, если да, позволяет ContextMenu обработать ключ команды. The ProcessCmdKey method first determines whether the control has a ContextMenu, and if so, enables the ContextMenu to process the command key. Если клавиша Command не является ярлыком меню и у элемента управления есть родительский элемент, ключ передается в ProcessCmdKey метод родителя. If the command key is not a menu shortcut and the control has a parent, the key is passed to the parent’s ProcessCmdKey method. В результате используются клавиши команд «пузырьковая» в иерархии элементов управления. The net effect is that command keys are «bubbled» up the control hierarchy. В дополнение к нажатию клавиши пользователем, ключевые данные также указывают, какие клавиши модификатора были нажаты в то же время, что и ключ. In addition to the key the user pressed, the key data also indicates which, if any, modifier keys were pressed at the same time as the key. К клавишам модификатора относятся клавиши SHIFT, CTRL и ALT. Modifier keys include the SHIFT, CTRL, and ALT keys.

Примечания для тех, кто наследует этот метод

При переопределении ProcessCmdKey(Message, Keys) метода в производном классе элемент управления должен вернуться, true чтобы показать, что он обработал ключ. When overriding the ProcessCmdKey(Message, Keys) method in a derived class, a control should return true to indicate that it has processed the key. Для ключей, которые не обрабатываются элементом управления, должен возвращаться результат вызова метода базового класса ProcessCmdKey(Message, Keys) . For keys that are not processed by the control, the result of calling the base class’s ProcessCmdKey(Message, Keys) method should be returned. При необходимости элементы управления будут переопределять этот метод. Controls will seldom, if ever, need to override this method.

Control. Key Press Событие

Определение

Происходит при нажатии клавиши с буквой, Occurs when a character. пробела или клавиши BACKSPACE, если фокус находится в элементе управления. space or backspace key is pressed while the control has focus.

Тип события

Примеры

В следующем примере кода событие используется KeyPress для предотвращения ввода символов в элемент управления. The following code example uses the KeyPress event to prevent characters from entering the control.

В следующем примере кода демонстрируется порядок возрастания KeyDown событий, KeyUp и KeyPress , а также способы регистрации обработчиков событий для них. The following code example demonstrates the order of rising the KeyDown, KeyUp and KeyPress events, also how to register event handlers on them.

Комментарии

Ключевые события происходят в следующем порядке: Key events occur in the following order:

Это KeyPress событие не вызывается несимвольными ключами, отличными от пробела и Backspace; однако, несимвольные ключи вызывают KeyDown события и KeyUp . The KeyPress event is not raised by non-character keys other than space and backspace; however, the non-character keys do raise the KeyDown and KeyUp events.

Используйте KeyChar свойство для выборки сочетаний клавиш во время выполнения, а также для использования или изменения подмножества распространенных нажатий клавиш. Use the KeyChar property to sample keystrokes at run time and to consume or modify a subset of common keystrokes.

Читайте также:  Как удалить steam mac os

Чтобы обрабатывать события клавиатуры только на уровне формы и не включать другие элементы управления для получения событий клавиатуры, задайте KeyPressEventArgs.Handled для свойства в KeyPress методе обработки событий формы значение true . To handle keyboard events only at the form level and not enable other controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form’s KeyPress event-handling method to true .

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

C# — System.Windows.Forms.Keys — How to keep application hotkeys in one place

I have few «hotkeys» in my application. All «hotkeys» sequences are unique in application scope (so for example F12 key will always fire the same single task). In few places there are handled like here:

But I have idea to keep all keyboard shortcuts used in my app in one place. I was thinking to put them in Constants.cs file:

But how to achieve this in case of this sequence: e.Modifiers == Keys.Shift && e.KeyCode == Keys.Up

All advices how to store all application «hotkeys» definitions in one place are welcome 🙂 So one day if I need to change Keys.F12 to Keys.F10 I will be able to just edit it in one place instead of search&replace tool..

1 Answer 1

A complete solution to this would be to use some form of Command Management, where you define application-wide commands and (optionally) assign hot-keys to them.

WPF has support for Command Management built-in, and you can roll out your own without too much effort.

If you don’t want to go down that route, you can create an application-wide filter for key messages, and work with those.

Below is code for a KeyStore class. It’s a singleton class that acts as a message filter for keys.

To use it, first assign the key filter to the Application class. In your Main() method (probably in the Program.cs file), add the following line before Application.Run():

Make sure this line is inserted before Application.Run(). This registers the KeyStore as a key handler.

Then, you can add keys to the KeyStore anywhere you want, for example in the Form_Load of your main form:

This registers two combinations: F12 and Control+S.

Then, register an event handler so you can capture the CloseApp and Save key presses.

In my example code, I used MessageBox.Show() to prove that the event was fired:

You can register or unregister event handlers at will, when forms are opened and closed for example, or have application-wide handlers. It’s up to you.

Keys Enum

Definition

Specifies key codes and modifiers.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

Fields

The ALT modifier key.

The application key (Microsoft Natural Keyboard).

The BACKSPACE key.

The browser back key.

The browser favorites key.

The browser forward key.

The browser home key.

The browser refresh key.

The browser search key.

The browser stop key.

The CAPS LOCK key.

The CAPS LOCK key.

The CTRL modifier key.

The decimal key.

The DOWN ARROW key.

The ERASE EOF key.

The EXECUTE key.

The IME final mode key.

The IME Hanguel mode key. (maintained for compatibility; use HangulMode )

The IME Hangul mode key.

The IME Hanja mode key.

The IME accept key, replaces IMEAceept.

The IME accept key. Obsolete, use IMEAccept instead.

The IME convert key.

The IME mode change key.

The IME nonconvert key.

The IME Junja mode key.

The IME Kana mode key.

The IME Kanji mode key.

The bitmask to extract a key code from a key value.

The start application one key.

The start application two key.

The launch mail key.

The left mouse button.

The left CTRL key.

The LEFT ARROW key.

The LINEFEED key.

The left ALT key.

The left SHIFT key.

The left Windows logo key (Microsoft Natural Keyboard).

The middle mouse button (three-button mouse).

Читайте также:  Неверная контрольная сумма mac os

The media next track key.

The media play pause key.

The media previous track key.

The media Stop key.

The bitmask to extract modifiers from a key value.

The multiply key.

The PAGE DOWN key.

A constant reserved for future use.

The NUM LOCK key.

The 0 key on the numeric keypad.

The 1 key on the numeric keypad.

The 2 key on the numeric keypad.

The 3 key on the numeric keypad.

The 4 key on the numeric keypad.

The 5 key on the numeric keypad.

The 6 key on the numeric keypad.

The 7 key on the numeric keypad.

The 8 key on the numeric keypad.

The 9 key on the numeric keypad.

The OEM 102 key.

The OEM angle bracket or backslash key on the RT 102 key keyboard.

The OEM close bracket key on a US standard keyboard.

The OEM comma key on any country/region keyboard.

The OEM minus key on any country/region keyboard.

The OEM open bracket key on a US standard keyboard.

The OEM period key on any country/region keyboard.

The OEM pipe key on a US standard keyboard.

The OEM plus key on any country/region keyboard.

The OEM question mark key on a US standard keyboard.

The OEM singled/double quote key on a US standard keyboard.

The OEM Semicolon key on a US standard keyboard.

The OEM tilde key on a US standard keyboard.

Used to pass Unicode characters as if they were keystrokes. The Packet key value is the low word of a 32-bit virtual-key value used for non-keyboard input methods.

The PAGE DOWN key.

The PAGE UP key.

The PRINT SCREEN key.

The PAGE UP key.

The PROCESS KEY key.

The right mouse button.

The right CTRL key.

The RIGHT ARROW key.

The right ALT key.

The right SHIFT key.

The right Windows logo key (Microsoft Natural Keyboard).

The SCROLL LOCK key.

The select media key.

The separator key.

The SHIFT modifier key.

The computer sleep key.

The PRINT SCREEN key.

The SPACEBAR key.

The subtract key.

The UP ARROW key.

The volume down key.

The volume mute key.

The volume up key.

The first x mouse button (five-button mouse).

The second x mouse button (five-button mouse).

Examples

The following code example uses the KeyDown event to determine the type of character entered into the control.

Remarks

The Keys class contains constants for processing keyboard input. The members of the Keys enumeration consist of a key code and a set of modifiers combined into a single integer value. In the Win32 application programming interface (API) a key value has two halves, with the high-order bits containing the key code (which is the same as a Windows virtual key code), and the low-order bits representing key modifiers such as the SHIFT, CONTROL, and ALT keys.

Do not use the values in this enumeration for combined bitwise operations. The values in the enumeration are not mutually exclusive.

This enumeration provides no way to test whether the CAPS LOCK or NUM LOCK keys are currently activated. You can use one of the following techniques to determine if these keys are activated:

Call the IsKeyLocked method of the Control class.

For finer control, use the Windows API functions GetKeyState , GetAsyncKeyState , or GetKeyboardState defined in user32.dll, to do this. For more information about calling native functions, see Consuming Unmanaged DLL Functions.

The following table shows the key code values represented by two enumerated values, representing both the general original equipment manufacturer (OEM) keys and the more specific U.S.-keyboard associations.

Hexadecimal value U.S. keyboard General OEM
BA OemSemicolon Oem1
BF OemQuestion Oem2
C0 Oemtilde Oem3
DB OemOpenBrackets Oem4
DC OemPipe Oem5
DD OemCloseBrackets Oem6
DE OemQuotes Oem7
E2 OemBackslash Oem102

For the .NET Framework 2.0, a member IMEAccept was added that supersedes the previous entry, IMEAceept, which was spelled incorrectly. The older version has been retained for backward compatibility, but it may be deleted in future versions of the .NET Framework

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