SendKeys
Sends keyboard actions to the active window.
void SendKeys(string text);
Parameters
text:
The keys to be send to the active window. The keys must follow the syntax described below.
SendKeys might throw KeySequenceError if an error is found when reading keys. SendKeys reads all keys before pressing any, so if an error is found, no keys will be pressed.
Key Syntax
Modifiers
SendKeys takes a string specifying one or more keys to press. Most letter, number, and punctuation keys are represented by the corresponding characters, but the following keys and characters have special meaning:
Key | Meaning |
---|---|
+ | Shift |
^ | Ctrl |
% | Alt |
# | Left WindowKey |
To apply one or more modifiers to a key, place it in front of that key. For example, here's how to get Control + a:
^a
To use one of the modifier keys, escape it by surrounding it with curly braces {
and }
. For example, for a literal %
instead of ALT
:
{%}
All of the following must be escaped within curly braces:
+ ^ % ~ { } [ ]
Each character must be escaped individually. You cannot do the following:
{%%}
When possible, SendKeys will automatically press Shift for you. This easier for the programmer to read and write. For example, if you want SendKeys to type ABC!!, rather than using this:
+a+b+c+1+1
you can use:
ABC!!
Key Codes
For keys that don't have a character representation, you must use a code. Here are the codes SendKeys recognizes:
Key | Code |
---|---|
Backspace | {BACKSPACE} , {BACK} , {BS} , or {BKSP} |
Break | {BREAK} |
Caps Lock | {CAPSLOCK} or {CAP} |
DEL or Delete | {DELETE} or {DEL} |
Down arrow | {DOWN} |
End | {END} |
Enter | {ENTER} |
ESC | {ESC} |
Help | {HELP} |
Home | {HOME} |
INS or Insert | {INSERT} or {INS} |
Left arrow | {LEFT} |
NUM Lock | {NUMLOCK} |
Page down | {PGDN} |
Page up | {PGUP} |
Print screen | {PRTSC} |
Right arrow | {RIGHT} |
Scroll lock | {SCROLLLOCK} |
Space bar | {SPACE} |
Tab | {TAB} |
Up arrow | {UP} |
F1 | {F1} |
F2 | {F2} |
F3 | {F3} |
F4 | {F4} |
F5 | {F5} |
F6 | {F6} |
F7 | {F7} |
F8 | {F8} |
F9 | {F9} |
F10 | {F10} |
F11 | {F11} |
F12 | {F12} |
F13 | {F13} |
F14 | {F14} |
F15 | {F15} |
F16 | {F16} |
F17 | {F17} |
F18 | {F18} |
F19 | {F19} |
F20 | {F20} |
F21 | {F21} |
F22 | {F22} |
F23 | {F23} |
F24 | {F24} |
Keypad add | {ADD} |
Keypad subtract | {SUBTRACT} |
Keypad multiply | {MULTIPLY} |
Keypad divide | {DIVIDE} |
Left Windows(R) | {LWIN} |
Right Windows(R) | {RWIN} |
Modifiers can used with codes as well. For example, for Ctrl + Shift + Home:
^+{HOME}
Examples
Entering values in a login dialog.
SendKeys("username{TAB}password{ENTER}")
Known Issues
If NUMLOCK is on when SendKeys is called, certain keystroke combinations don't work. For example, C + Shift + Left (or ^+{Left})
doesn't select text in notepad. Instead, the cursor is moved one to the left as if Shift hadn't been pressed.
Related: