30.6. Communicating via SendKeys

The SendKeys statement is a basic and limited form of communication with other applications. You may find SendKeys useful if neither Automation nor DDE works with the target application.

SendKeys sends the specified keystrokes to the destination application. For example, to use SendKeys to send the command to create a new file in Notepad, you send the keystrokes for Alt+F, N (to execute the File New command), and Notepad reacts as if you had pressed the keys manually. Interestingly, Alt+F also works in many Vista applications; in Office 2007 applications, Alt+F imitates clicking the Office button, for example.

SendKeys works only with currently running Windows applications: you can't use SendKeys to start another application (for that you need to use Shell, as discussed earlier in this chapter), nor can you use SendKeys to communicate with DOS applications running in virtual DOS machines under Windows.

The syntax for the SendKeys statement is as follows:

SendKeys string[, wait]

Here, string is a required String expression specifying the keystrokes to be sent to the destination application. wait is an optional Boolean value specifying whether to wait after sending the keystrokes until the application has executed them (True) or to immediately return control to the procedure sending the keystrokes (False, the default setting). The True setting, however, can prevent some kinds of timing problems.

Typically, string consists of a series of keystrokes (rather than a single keystroke). All alphanumeric characters that appear on the regular keyboard are represented by the characters themselves: to send the letter H, you specify H in the string, and to send the word Hello, you specify Hello in the string. To denote the movement and editing keys, SendKeys uses keywords enclosed within braces ({}), as described in Table 30.2.

Table 30.2. SendKeys Keywords for Movement and Editing Keys
KeyCode
,{DOWN}
fl{LEFT}
{RIGHT}
·{UP}
Backspace{BACKSPACE}, {BS}, or {BKSP}
Break{BREAK}
Caps Lock{CAPSLOCK}
Delete{DELETE} or {DEL}
End{END}
Enter{ENTER}
Esc{ESC}
F1, F2, etc.{F1}, {F2}, etc. (up to {F16})
Help{HELP}
Home{HOME}
Insert{INSERT} or {INS}
Num Lock{NUMLOCK}
Page Down{PGDN}
Page Up{PGUP}
Print Screen{PRTSC}
Scroll Lock{SCROLLLOCK}
Tab{TAB}

To send meta keys, use the symbols shown in Table 30.3.

Table 30.3. SendKeys Symbols for Meta Keys
KeyCode
Shift+
Ctrl^
Alt%

SendKeys automatically assigns the keystroke after the meta key to the meta key. For example, to send a Ctrl+O keystroke, you specify ^O, and SendKeys assigns the O to the Ctrl keystroke; the next keystroke after the O is considered to be struck separately. If you need to assign multiple keystrokes to the meta key, enter the keystrokes in parentheses after the meta key. For example, to send Alt+F, Alt+I, Alt+I, you'd specify %(FII) rather than %FII .

SendKeys has special meanings for the plus sign (+), caret (^), percent sign (%), and parentheses (); the tilde (~) gets special treatment as well. To use these characters to represent themselves, enter them within braces: {+} sends a regular = sign, {^} a regular caret, {%} a percent sign, {~} a tilde, and {()} parentheses. Likewise, you must enclose brackets (which have a special meaning in DDE in some applications) within braces; braces themselves also go within braces.

Using SendKeys is much less complex than these details initially make it appear — and with that reassurance, there's one more trick you should know: to repeat a key, enter the key and the number of repetitions in braces. For example, to send five ↑ keystrokes, you'd specify {UP 5 }; to send 10 zeroes, you'd specify {0 10 }.

Listing 30-4 shows an example of using SendKeys to start Notepad and send log-file information to it.

You Can't Step Through SendKeys Code

Because SendKeys needs to activate the target application, you can't step into the code (repeatedly pressing F8) in the Visual Basic Editor—the Editor grabs the focus back at the wrong point, directing the keystrokes toward itself rather than the target application. Instead, you must run the procedure, either from the Visual Basic Editor (by pressing F5) or from the host application as a macro.


Example 30.4. Listing 30.4
1.   Sub Send  to  Notepad()
 2.      Dim strLogDate As String
 3.      Dim strSaveLog As String
 4.      Dim strMsg As String
 5.      Dim appNotepad As Variant
 6.      strMsg = "Sample log text here."
 7.      strLogDate = Month(Now) & "-" & Day(Now) & "-" & Year(Now)
 8.      strSaveLog = "Log file for " & strLogDate & ".txt"
 9.      appNotepad = Shell("notepad.exe", vbNormalFocus)
10.       AppActivate appNotepad
11.       SendKeys strMsg & "%FS" & strSaveLog & "{Enter} " & "%{F4}", True
12.   End Sub

Here's how the code works:

  • The Send_to_Notepad procedure starts by declaring (in lines 2, 3, and 4) three String variables — strLogDate, strSaveLog, and strMsg — and (in line 5) one Variant variable, appNotepad.

  • Line 6 then assigns to strMsg a sample string of text.

  • Line 7 assigns to strLogDate a date built of the Day, Month, and Year values for Now (which returns the current date and time). For example, if the date is July 11, 2008, Month(Now) will return 7, Day(Now) will return 11, and Year(Now) will return 2008, so the strLogDate string will contain 7-11-2008.

  • Line 8 then assigns to the strSaveLog string (which will be used to supply the filename for the log file) text describing the file, the strLogDate string, and the .txt extension (to continue our example, Log file for 7-11-2008.txt).

  • In line 9, the procedure finally gets down to business, using the Shell statement to run Notepad in a "normal" (not maximized or minimized) window with focus and storing the task ID of the Notepad session in the variable appNotepad.

  • Line 10 then uses an AppActivate statement to activate Notepad.

  • Line 11 uses a SendKeys statement to send to Notepad the following:

    • The information contained in the String variable strMsg.

    • An Alt+F keystroke (to pull down the File menu), followed by an S keypress to choose the Save item on the menu. This keypress displays the Save As dialog box with the File Name text box selected.

    • The strSaveLog String variable, which is entered in the File Name text box.

    • An Enter keypress to choose the Save button in the Save As dialog box.

    • An Alt+F4 keystroke to quit Notepad.

  • Line 12 ends the procedure.

When you run this procedure (again, you need to run the procedure by pressing F5, rather than stepping into it with F8), you'll see the following:

  1. Notepad springs to life.

  2. The contents of the Msg string appear in the Notepad window.

  3. The Save As dialog box displays itself, enters the filename in the File Name text box, and then dismisses itself.

  4. Notepad closes.

Because SendKeys was historically most often employed to open an application's menus and select an option from the menus, you might think that Vista applications — which are largely menu-free — would seriously curtail the flexibility of the SendKeys technique. However, this isn't true. Many of the features of the Vista Ribbon, for example, are accessible via key combinations. For example, pressing the sequence Alt, W, Q, 2, and the Enter key in Word will switch to the View tab on the Ribbon, select the Zoom option, and switch to a 200% zoom. The difference here is that instead of employing the traditional approach of simultaneously pressing the Alt key while pressing other keys (such as Alt+V to open a View menu), in Vista you press and release Alt by itself, then you press the W key to switch to the View tab on the Ribbon. At this point, additional keypresses are possible to activate the various options on the View tab.

Here's another code example, which illustrates how to manipulate Vista-style applications. This time Excel, not Notepad, is the target, and the Vista Ribbon is manipulated. You send an Alt key by itself (this activates the shortcut key feature on the Ribbon and the Quick Access Toolbar as well, displaying a variety of keys you can choose from). Then in the following procedure you switch to the View tab (a W does that), and finally you select full-screen mode by sending E:

Sub Send_to_Excel()

    Dim appExcel As Variant

    appExcel = Shell("Excel.exe", vbNormalFocus)
    AppActivate appExcel

        SendKeys "%", True 'send Alt by itself
    SendKeys "W", True 'W for the View tab
    SendKeys "E", True 'E for full screen mode

    End Sub

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.151.252