JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Sending Keystrokes to Other Programs

This one isn't a part of form handling, but it's a part of System.Windows.Forms, and it's one of my absolutely favorite parts of Visual Basic—SendKeys, which you can use to send keystrokes to other applications. Say it's time to print out the 349 screen spreadsheets you've created in your new spreadsheet program to show the boss. Regrettably, there just doesn't seem to be any way to print them out except one at a time, using the File menu's Print item. Can Visual Basic help here?

Yes. You can use the SendKeys function to send keys to the program that currently has the Windows focus, just as if you typed in those keys yourself. Using Alt keys, you can reach the menu items in your spreadsheet's File menu. The day is saved, because now you can automate your printing job. If the keys you want to send are not simple text, just embed the codes you see in Table 4.5 in the text you send to SendKeys.

Table 4.5: SendKeys Key Codes.

Key

Code

Backspace

{BACKSPACE}, {BS}, or {BKSP}

Break

{BREAK}

Caps Locl

{CAPSLOCK}

Del or Delete

{DELETE} or {DEL}

Down Arrow

{DOWN}

End

{END}

Enter/Return

{ENTER}or ~

Esc

{ESC}

Help

{HELP}

Home

{HOME}

Ins or Insert

{INSERT} or {INS}

Left Arrow

{LEFT}

Numloick

{NUMLOCK}

Page Down

{PGDN}

Page Up

{PGUP}

Print Screen

{PRTSC}

Right Arrow

{RIGHT}

Scroll Lock

{SCROLLLOCK}

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}

Shift

+

Ctrl

^

Alt

%

Here's an example showing how to use SendKeys. I'll give the Windows WordPad program the focus with the Visual Basic AppActivate function, passing it the title of that program (which appears in its title bar), and send the string "Hello from Visual Basic" to that program as follows:

Public Class Form1
    Inherits System.Windows.Forms.Form

'Windows Form Designer generated code

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        AppActivate("Document - WordPad")
        System.Windows.Forms.SendKeys.Send("Hello from Visual Basic!")
    End Sub
End Class

The result appears in Figure 4.26—now we're able to send keystrokes to an-other program.

Click To expand
Figure 4.26: Sending keystrokes to Windows WordPad.
Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor