Sending and Receiving Messages

Messages make Windows tick, but you wouldn’t know it from studying the Visual Basic documentation. Take keyboard events. If you press the B key while a Visual Basic text box has the focus, Windows sends WM_KEYDOWN, WM_CHAR, and WM_KEYUP messages to the text box. But your Visual Basic program sees these messages as the KeyDown, KeyPress, and KeyUp events.

In Visual Basic, most events are caused by Windows messages. Sometimes you’ll find a one-to-one mapping, as with the keyboard messages just mentioned. A Form_Load event, however, doesn’t correspond directly to a specific message. If you’re curious and you happen to have a C or a Pascal compiler, you can use a message filter utility (such as Microsoft’s Spy++) to see exactly which messages are being sent to which windows. You’ll get bored fast watching these C messages. A Visual Basic event spy might be more interesting. You should be qualified to write one by the time you finish this book.

Hardcore Basic programmers can go beyond the events Visual Basic provides and handle their own messages. Sending messages is relatively easy to do with Windows API calls. Receiving messages, however, is a more difficult problem. It used to require a message capture component (and some programmers might still find this easier), but starting with Visual Basic version 5, you can also receive messages by using the AddressOf operator to redirect them to your own window procedures.