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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.