System windows form keys

Практическое руководство. Обработка ввода с клавиатуры на уровне формы How to: Handle Keyboard Input at the Form Level

Windows Forms предоставляет возможность обработки сообщений клавиатуры на уровне формы, прежде чем они достигнут элемента управления. Windows Forms provides the ability to handle keyboard messages at the form level, before the messages reach a control. В этом разделе показано, как выполнить данную задачу. This topic shows how to accomplish this task.

Обработка ввода с клавиатуры на уровне формы To handle a keyboard message at the form level

Чтобы сообщения клавиатуры принимались формой, прежде чем они достигнут элементов управления в форме, нужно обработать события KeyPress или KeyDown начальной формы и присвоить свойству формы KeyPreview значение true . Handle the KeyPress or KeyDown event of the startup form, and set the KeyPreview property of the form to true so that keyboard messages are received by the form before they reach any controls on the form. В следующем примере кода обрабатывается событие KeyPress посредством обнаружения всех цифровых клавиш и использования «1», «4» и «7». The following code example handles the KeyPress event by detecting all of the number keys and consuming ‘1’, ‘4’, and ‘7’.

Пример Example

В следующем примере кода представлено завершенное приложение для предыдущего примера кода. The following code example is the entire application for the above example. Приложение включает TextBox и несколько других элементов управления, предназначенных для перемещения фокуса ввода из TextBox. The application includes a TextBox along with several other controls that allow you to move focus from the TextBox. Событие KeyPress основной формы Form использует «1», «4» и «7», а событие KeyPress в TextBox использует «2», «5» и «8», остальные клавиши отображаются. The KeyPress event of the main Form consumes ‘1’, ‘4’, and ‘7’, and the KeyPress event of the TextBox consumes ‘2’, ‘5’, and ‘8’ while displaying the remaining keys. Сравните выходные данные MessageBox при нажатии цифровой клавиши, когда фокус ввода установлен на TextBox с выходными данными MessageBox при нажатии цифровой клавиши, когда фокус ввода установлен на одном из других элементов управления. Compare the MessageBox output when you press a number key while the TextBox has focus with the MessageBox output when you press a number key while focus is on one of the other controls.

Компиляция кода Compiling the Code

Для этого примера требуются: This example requires:

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).

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

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.

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.

Key Перечисление

Определение

Задает возможные значения клавиш на клавиатуре. Specifies the possible key values on a keyboard.

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

Клавиша ABNT_C1 (Бразилия). The ABNT_C1 (Brazilian) key.

Клавиша ABNT_C2 (Бразилия). The ABNT_C2 (Brazilian) key.

Клавиша сложения. The Add key.

Клавиша приложения (клавиатура Microsoft Natural Keyboard). The Application key (Microsoft Natural Keyboard). Также называется клавишей меню, так как с ее помощью отображается контекстное меню приложения. Also known as the Menu key, as it displays an application-specific context menu.

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

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

Клавиша BACKSPACE. 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.

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

Клавиша «Отмена». The Cancel key.

Клавиша CAPS LOCK. The Caps Lock key.

Клавиша CAPS LOCK. The Caps Lock key.

Клавиша CLEAR. The Clear key.

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

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

Клавиша 0 (нуль). The 0 (zero) key.

Клавиша 1 (один). The 1 (one) key.

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

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

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

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

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

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

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

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

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

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

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

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

DbeEnterDialogConversionMode 170

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

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

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

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

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

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

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

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

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

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

Клавиша используется вместе с другой клавишей для создания одного объединенного символа. The key is used with another key to create a single combined character.

Клавиша десятичного разделителя. The Decimal key.

Клавиша DELETE. The Delete key.

Клавиша деления. The Divide key.

Клавиша СТРЕЛКА ВНИЗ. The Down Arrow key.

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

Клавиша END. The End key.

Клавиша ВВОД. The Enter key.

Клавиша ERASE EOF. The ERASE EOF key.

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

Клавиша «Выполнить». The Execute key.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Клавиша режима «Последний» редактора метода ввода. The IME Final mode key.

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

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

Клавиша режима «Хангыль» редактора метода ввода. The IME Hangul mode key.

Клавиша режима «Ханджа» редактора метода ввода. The IME Hanja mode key.

Клавиша справки. The Help key.

Клавиша HOME. The Home key.

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

Клавиша принятия в редакторе метода ввода. The IME Accept key.

Клавиша преобразования в редакторе метода ввода. The IME Convert key.

Запрос на изменение режима редактора метода ввода. The IME Mode change request.

Клавиша без преобразования в редакторе метода ввода. The IME NonConvert key.

Специальная клавиша, маскирующая фактическую клавишу, обрабатываемую редактором метода ввода. A special key masking the real key being processed by an IME.

Клавиша INSERT. The Insert key.

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

Клавиша режима «Джунджа» редактора метода ввода. The IME Junja mode key.

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

Клавиша режима «Кана» редактора метода ввода. The IME Kana mode key.

Клавиша режима «Кандзи» редактора метода ввода. The IME Kanji mode key.

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

Клавиша запуска приложения 1. The Launch Application1 key.

Клавиша запуска приложения 2. The Launch Application2 key.

Клавиша запуска почты. The Launch Mail key.

Клавиша СТРЕЛКА ВЛЕВО. The Left Arrow key.

Левая клавиша ALT. The left ALT key.

Левая клавиша CTRL. The left CTRL key.

Левая клавиша SHIFT. The left Shift key.

Клавиша перевода строки. The Linefeed key.

Левая клавиша с логотипом Windows (клавиатура Microsoft Natural Keyboard). The left Windows logo key (Microsoft Natural Keyboard).

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

Клавиша «Следующая запись». The Media Next Track key.

Клавиша приостановки воспроизведения. The Media Play Pause key.

Клавиша «Предыдущая запись». The Media Previous Track key.

Клавиша остановки воспроизведения. The Media Stop key.

Клавиша умножения. The Multiply key.

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

Клавиша PAGE DOWN. The Page Down key.

Константа, зарезервированная для будущего использования. A constant reserved for future use.

Нет нажатых клавиш. No key pressed.

Клавиша NUM LOCK. The Num Lock key.

Клавиша 0 на цифровой клавиатуре. The 0 key on the numeric keypad.

Клавиша 1 на цифровой клавиатуре. The 1 key on the numeric keypad.

Клавиша 2 на цифровой клавиатуре. The 2 key on the numeric keypad.

Клавиша 3 на цифровой клавиатуре. The 3 key on the numeric keypad.

Клавиша 4 на цифровой клавиатуре. The 4 key on the numeric keypad.

Клавиша 5 на цифровой клавиатуре. The 5 key on the numeric keypad.

Клавиша 6 на цифровой клавиатуре. The 6 key on the numeric keypad.

Клавиша 7 на цифровой клавиатуре. The 7 key on the numeric keypad.

Клавиша 8 на цифровой клавиатуре. The 8 key on the numeric keypad.

Клавиша 9 на цифровой клавиатуре. The 9 key on the numeric keypad.

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

Клавиша OEM 1. The OEM 1 key.

Клавиша OEM 102. The OEM 102 key.

Клавиша OEM 2. The OEM 2 key.

Клавиша OEM 3. The OEM 3 key.

Клавиша OEM 4. The OEM 4 key.

Клавиша OEM 5. The OEM 5 key.

Клавиша OEM 6. The OEM 6 key.

Клавиша OEM 7. The OEM 7 key.

Клавиша OEM 8. The OEM 8 key.

Клавиша OEM ATTN. The OEM ATTN key.

Клавиша OEM AUTO. The OEM AUTO key.

Клавиша OEM с обратной косой чертой. The OEM Backslash key.

Клавиша OEM BACKTAB. The OEM BACKTAB key.

Клавиша OEM очистки. The OEM Clear key.

Клавиша OEM с закрывающими скобками. The OEM Close Brackets key.

Клавиша OEM с запятой. The OEM Comma key.

Клавиша OEM COPY. The OEM COPY key.

Клавиша OEM ENLW. The OEM ENLW key.

Клавиша OEM FINISH. The OEM FINISH key.

Клавиша OEM с минусом. The OEM Minus key.

Клавиша OEM с открывающими скобками. The OEM Open Brackets key.

Клавиша OEM с точкой. The OEM Period key.

Клавиша OEM с вертикальной чертой. The OEM Pipe key.

Клавиша OEM со сложением. The OEM Addition key.

Клавиша OEM с вопросительным знаком. The OEM Question key.

Клавиша OEM с кавычками. The OEM Quotes key.

Клавиша OEM с точкой с запятой. The OEM Semicolon key.

Клавиша OEM с тильдой. The OEM Tilde key.

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

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

Клавиша PAGE DOWN. The Page Down key.

Клавиша PAGE UP. The Page Up key.

Клавиша паузы. The Pause key.

Клавиша ВОСПРОИЗВЕСТИ. The PLAY key.

Клавиша «Печать». The Print key.

Клавиша PRINT SCREEN. The Print Screen key.

Клавиша PAGE UP. The Page Up key.

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

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

Клавиша RETURN. The Return key.

Клавиша СТРЕЛКА ВПРАВО. The Right Arrow key.

Правая клавиша ALT. The right ALT key.

Правая клавиша CTRL. The right CTRL key.

Правая клавиша SHIFT. The right Shift key.

Правая клавиша с логотипом Windows (клавиатура Microsoft Natural Keyboard). The right Windows logo key (Microsoft Natural Keyboard).

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

Клавиша SCROLL LOCK. The Scroll Lock key.

Клавиша «Выбрать». The Select key.

Клавиша выбора мультимедиа. The Select Media key.

Клавиша разделителя. The Separator key.

Клавиша перевода компьютера в спящий режим. The Computer Sleep key.

Клавиша PRINT SCREEN. The Print Screen key.

Клавиша ПРОБЕЛ. The Spacebar key.

Клавиша вычитания. The Subtract key.

Специальный клавиша, маскирующая фактическую клавишу, обрабатываемую в качестве системной клавиши. A special key masking the real key being processed as a system key.

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

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

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

Клавиша СТРЕЛКА ВВЕРХ. The Up Arrow key.

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

Клавиша уменьшения громкости. The Volume Down key.

Клавиша выключения звука. The Volume Mute key.

Клавиша увеличения громкости. The Volume Up key.

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

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

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

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

Клавиша МАСШТАБ. The ZOOM key.

Комментарии

Сведения, относящиеся к вводу ключа, можно получить несколькими различными способами в WPF. Information pertaining to key input can be obtained in several different ways in WPF. События, связанные с ключами, такие как KeyDown и KeyUp , предоставляют сведения о состоянии ключа через KeyEventArgs объект, передаваемый обработчику событий. Key-related events, such as KeyDown and KeyUp, provide key state information through the KeyEventArgs object that is passed to the event handler. Сведения о состоянии ключа также можно получить с помощью статических методов Keyboard класса, таких как IsKeyUp и GetKeyStates . Key state information can also be obtained through the static methods on the Keyboard class, such as IsKeyUp and GetKeyStates. KeyboardКласс сообщает о текущем состоянии клавиатуры. The Keyboard class reports the current state of the keyboard.

Читайте также:  Доступно мало оперативной памяти windows 10
Оцените статью