Send Keystrokes to an Application

Problem

You want to interact with an application programmatically by sending keystrokes.

Solution

Use the WshShell.SendKeys method from the Windows Script Host. Alternatively, use the SendKeys class in the System.Windows.Forms namespace, in conjunction with the FindWindow and SetForegroundWindow methods from the Win32 API.

Discussion

Ideally, application interaction should work through known interfaces. For example, you can "drive" Microsoft Office using dedicated Office COM components, as described in Chapter 19. However, many applications don’t expose any programmatic interface, in which case, the only way you can interact with the application is by sending keystrokes to the user interface.

There is more than one ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.