Send Keys. Send(String) Method
Definition
Sends keystrokes to the active application.
Parameters
The string of keystrokes to send.
Exceptions
There is not an active application to send keystrokes to.
keys does not represent valid keystrokes
Examples
The following code example demonstrates how to use the Send method.To run the example, paste the following code in a form called Form1 containing a button called Button1. Ensure the click events are associated with their event-handling methods in this example. The button control’s TabIndex property should be set to 0. When the example is running, double-click the form to trigger the button’s click event.
Remarks
Each key is represented by one or more characters. To specify a single keyboard character, use the character itself. For example, to represent the letter A, pass in the string «A» to the method. To represent more than one character, append each additional character to the one preceding it. To represent the letters A, B, and C, specify the parameter as «ABC».
The plus sign (+), caret (^), percent sign (%), tilde (
), and parentheses () have special meanings to SendKeys. To specify one of these characters, enclose it within braces (<>). For example, to specify the plus sign, use «<+>«. To specify brace characters, use «<<>» and «<>>». Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces. In other applications, brackets do have a special meaning that might be significant when dynamic data exchange (DDE) occurs.
If your application is intended for international use with a variety of keyboards, the use of Send could yield unpredictable results and should be avoided.
To specify characters that aren’t displayed when you press a key, such as ENTER or TAB, and keys that represent actions rather than characters, use the codes in the following table.
Key | Code |
---|---|
BACKSPACE | |
BREAK | |
CAPS LOCK | |
DEL or DELETE | |
DOWN ARROW | |
END | |
ENTER | |
ESC | |
HELP | |
HOME | |
INS or INSERT | |
LEFT ARROW | |
NUM LOCK | |
PAGE DOWN | |
PAGE UP | |
PRINT SCREEN | |
RIGHT ARROW | |
SCROLL LOCK | |
TAB | |
UP ARROW | |
F1 | |
F2 | |
F3 | |
F4 | |
F5 | |
F6 | |
F7 | |
F8 | |
F9 | |
F10 | |
F11 | |
F12 | |
F13 | |
F14 | |
F15 | |
F16 | |
Keypad add | |
Keypad subtract | |
Keypad multiply | |
Keypad divide |
To specify keys combined with any combination of the SHIFT, CTRL, and ALT keys, precede the key code with one or more of the following codes.
Key | Code |
---|---|
SHIFT | + |
CTRL | ^ |
ALT | % |
To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use «+(EC)». To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use «+EC».
To specify repeating keys, use the form
Because there is no managed method to activate another application, you can either use this class within the current application or use native Windows methods, such as FindWindow and SetForegroundWindow , to force focus on other applications.
The SendKeys class has been updated for the .NET Framework 3.0 to enable its use in applications that run on Windows Vista. The enhanced security of Windows Vista (known as User Account Control or UAC) prevents the previous implementation from working as expected.
The SendKeys class is susceptible to timing issues, which some developers have had to work around. The updated implementation is still susceptible to timing issues, but is slightly faster and may require changes to the workarounds. The SendKeys class tries to use the previous implementation first, and if that fails, uses the new implementation. As a result, the SendKeys class may behave differently on different operating systems. Additionally, when the SendKeys class uses the new implementation, the SendWait method will not wait for messages to be processed when they are sent to another process.
If your application relies on consistent behavior regardless of the operating system, you can force the SendKeys class to use the new implementation by adding the following application setting to your app.config file.
To force the SendKeys class to use the previous implementation, use the value «JournalHook» instead.
Keys Перечисление
Определение
Задает коды и модификаторы клавиш. Specifies key codes and modifiers.
Это перечисление имеет атрибут FlagsAttribute, который разрешает побитовое сочетание значений его элементов.
Клавиша A. The A key.
Клавиша сложения. The add key.
Клавиша ALT. The ALT modifier key.
Клавиша контекстного меню (клавиатура Microsoft Natural). The application key (Microsoft Natural Keyboard).
Клавиша 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.
Клавиша CTRL. The CTRL modifier key.
Клавиша CTRL. The CTRL key.
Клавиша CRSEL. The CRSEL key.
Клавиша D. The D key.
Клавиша 0. The 0 key.
Клавиша 1. The 1 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.
Клавиша десятичного разделителя. The decimal key.
Клавиша DEL. The DEL 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.
Клавиша EXECUTE. 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.
Клавиша окончательного режима IME. The IME final mode key.
Клавиша G. The G key.
Клавиша H. The H key.
Клавиша режима IME Hanguel The IME Hanguel mode key. (поддерживается для обеспечения совместимости; используйте клавишу HangulMode ). (maintained for compatibility; use HangulMode )
Клавиша режима «Хангыль» редактора метода ввода. The IME Hangul mode key.
Клавиша режима «Ханджа» редактора метода ввода. The IME Hanja mode key.
Клавиша HELP. The HELP key.
Клавиша HOME. The HOME key.
Клавиша I. The I key.
Клавиша принятия IME, заменяет клавишу IMEAceept. The IME accept key, replaces IMEAceept.
Клавиша принятия IME. The IME accept key. Является устаревшей, вместо нее используется клавиша IMEAccept. Obsolete, use IMEAccept instead.
Клавиша преобразования IME. The IME convert key.
Клавиша изменения режима IME. The IME mode change key.
Клавиша без преобразования IME. The IME nonconvert key.
Клавиша INS. The INS key.
Клавиша J. The J key.
Клавиша режима «Джунджа» редактора метода ввода. The IME Junja mode key.
Клавиша K. The K key.
Клавиша режима «Кана» редактора метода ввода. The IME Kana mode key.
Клавиша режима «Кандзи» редактора метода ввода. The IME Kanji mode key.
Битовая маска для извлечения кода клавиши из значения клавиши. The bitmask to extract a key code from a key value.
Клавиша L. The L key.
Клавиша запуска первого приложения. The start application one key.
Клавиша запуска второго приложения. The start application two key.
Клавиша запуска приложения почты. The launch mail key.
Левая кнопка мыши. The left mouse button.
Левая клавиша CTRL. The left CTRL key.
Клавиша СТРЕЛКА ВЛЕВО. The LEFT ARROW key.
Клавиша LINEFEED. The LINEFEED key.
Левая клавиша ALT. The left ALT key.
Левая клавиша SHIFT. The left SHIFT key.
Левая клавиша с логотипом Windows (клавиатура Microsoft Natural Keyboard). The left Windows logo key (Microsoft Natural Keyboard).
Клавиша M. The M key.
Средняя кнопка мыши (трехкнопочная мышь). 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.
Клавиша ALT. The ALT key.
Битовая маска для извлечения модификаторов из значения клавиши. The bitmask to extract modifiers from a key value.
Клавиша умножения. 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 с угловой скобкой или обратной косой чертой на клавиатуре RT со 102 клавишами. The OEM angle bracket or backslash key on the RT 102 key keyboard.
Клавиша CLEAR. The CLEAR key.
Клавиша OEM с закрывающей квадратной скобкой на клавиатуре со стандартной раскладкой «США». The OEM close bracket key on a US standard keyboard.
Клавиша OEM с запятой на клавиатуре для любой страны или региона. The OEM comma key on any country/region keyboard.
Клавиша OEM со знаком минус на клавиатуре для любой страны или региона. The OEM minus key on any country/region keyboard.
Клавиша OEM с открывающей квадратной скобкой на клавиатуре со стандартной раскладкой «США». The OEM open bracket key on a US standard keyboard.
Клавиша OEM с точкой на клавиатуре для любой страны или региона. The OEM period key on any country/region keyboard.
Клавиша OEM с вертикальной чертой на клавиатуре со стандартной раскладкой «США». The OEM pipe key on a US standard keyboard.
Клавиша OEM со знаком плюс на клавиатуре для любой страны или региона. The OEM plus key on any country/region keyboard.
Клавиша OEM со знаком вопроса на клавиатуре со стандартной раскладкой «США». The OEM question mark key on a US standard keyboard.
Клавиша OEM с одинарной/двойной кавычкой на клавиатуре со стандартной раскладкой «США». The OEM singled/double quote key on a US standard keyboard.
Клавиша OEM с двоеточием на клавиатуре со стандартной раскладкой «США». The OEM Semicolon key on a US standard keyboard.
Клавиша OEM со знаком тильды на клавиатуре со стандартной раскладкой «США». The OEM tilde key on a US standard keyboard.
Клавиша P. The P key.
Клавиша PA1. The PA1 key.
Используется для передачи символов в Юникоде в виде нажатия клавиш. Used to pass Unicode characters as if they were keystrokes. Значение клавиши пакета является младшим словом 32-разрядного виртуального значения клавиши, используемого для бесклавиатурных методов ввода. The Packet key value is the low word of a 32-bit virtual-key value used for non-keyboard input methods.
Клавиша PAGE DOWN. The PAGE DOWN key.
Клавиша PAGE UP. The PAGE UP key.
Клавиша PAUSE. The PAUSE key.
Клавиша ВОСПРОИЗВЕСТИ. The PLAY key.
Клавиша PRINT. The PRINT key.
Клавиша PRINT SCREEN. The PRINT SCREEN key.
Клавиша PAGE UP. The PAGE UP key.
Клавиша PROCESS KEY. The PROCESS KEY key.
Клавиша Q. The Q key.
Клавиша R. The R key.
Правая кнопка мыши. The right mouse button.
Правая клавиша CTRL. The right CTRL key.
Клавиша RETURN. The RETURN key.
Клавиша СТРЕЛКА ВПРАВО. The RIGHT ARROW key.
Правая клавиша ALT. The right ALT 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.
Клавиша SELECT. The SELECT key.
Клавиша выбора файла мультимедиа. The select media key.
Клавиша разделителя. The separator key.
Клавиша SHIFT. The SHIFT modifier key.
Клавиша SHIFT. The SHIFT key.
Клавиша перевода компьютера в спящий режим. The computer sleep key.
Клавиша PRINT SCREEN. The PRINT SCREEN key.
Клавиша ПРОБЕЛ. The SPACEBAR key.
Клавиша вычитания. The subtract 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.
Первая кнопка мыши (пятикнопочная мышь). The first x mouse button (five-button mouse).
Вторая кнопка мыши (пятикнопочная мышь). The second x mouse button (five-button mouse).
Клавиша Y. The Y key.
Клавиша Z. The Z key.
Клавиша МАСШТАБ. The ZOOM key.
Примеры
В следующем примере кода событие используется KeyDown для определения типа символа, введенного в элемент управления. The following code example uses the KeyDown event to determine the type of character entered into the control.
Комментарии
KeysКласс содержит константы для обработки ввода с клавиатуры. The Keys class contains constants for processing keyboard input. Члены перечисления Keys состоят из кода ключа и набора модификаторов, Объединенных в одно целое значение. The members of the Keys enumeration consist of a key code and a set of modifiers combined into a single integer value. В интерфейсе прикладного программирования (API) Win32 значение ключа имеет две половины, а старшие биты содержат код ключа (то же, что и код виртуального ключа Windows), а младшие биты, представляющие модификаторы ключа, такие как SHIFT, CONTROL и ALT. 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.
Это перечисление не дает возможности проверить, активированы ли в настоящее время клавиши CAPS LOCK или NUM LOCK. 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:
Вызовите метод IsKeyLocked класса Control . Call the IsKeyLocked method of the Control class.
Для более точного управления используйте функции Windows API GetKeyState , GetAsyncKeyState или GetKeyboardState определенные в user32.dll, для этого. For finer control, use the Windows API functions GetKeyState , GetAsyncKeyState , or GetKeyboardState defined in user32.dll, to do this. Дополнительные сведения о вызове собственных функций см. в разделе Использование неуправляемых функций DLL. For more information about calling native functions, see Consuming Unmanaged DLL Functions.
В следующей таблице показаны ключевые значения кода, представленные двумя перечисляемыми значениями, представляющими общие ключи изготовителя оборудования (OEM) и более конкретные связи с клавиатурой США. 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 BA | оемсемиколон OemSemicolon | OEM1 Oem1 |
BF BF | оемкуестион OemQuestion | Oem2 Oem2 |
C0 C0 | оемтилде Oemtilde | Oem3 Oem3 |
DB DB | оемопенбраккетс OemOpenBrackets | Oem4 Oem4 |
DC DC | оемпипе OemPipe | Oem5 Oem5 |
DD DD | оемклосебраккетс OemCloseBrackets | Oem6 Oem6 |
DE DE | оемкуотес OemQuotes | Oem7 Oem7 |
E2 E2 | оембаккслаш OemBackslash | Oem102 Oem102 |
Для платформа .NET Framework 2,0 был добавлен член Имеакцепт, заменяющий предыдущую запись Имеацеепт, которая была написана неправильно. For the .NET Framework 2.0, a member IMEAccept was added that supersedes the previous entry, IMEAceept, which was spelled incorrectly. Старая версия сохранена для обеспечения обратной совместимости, но может быть удалена в будущих версиях платформа .NET Framework The older version has been retained for backward compatibility, but it may be deleted in future versions of the .NET Framework