![]() ![]() | ||
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.
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.
![]() ![]() | ||