Sending Messages
To understand the point of messages, let’s look briefly at how you would write programs for Windows in Visual Basic if you had to write them from scratch the way you do in C. The main routine in every Visual Basic program would look something like this:
Dim msg as TMessage
Dim hForm As Long, hControl As Long
hForm = CreateWindow(“Form", iFormAttr, ...)
hControl = CreateWindow(“Control", iCtrlAttr, ...)
‘ Get next message from Windows queue
Do While GetMessage(msg)
‘ Send message to appropriate window
TranslateMessage(msg)
DispatchMessage(msg)
Loop
End
Fortunately, Visual Basic creates all the windows it needs—based on the forms you draw and the attributes you set rather than on the code you write—and then keeps reading messages and sending them out to the windows until it gets a WM_QUIT message. WM_QUIT is the only message that causes GetMessage to return False and terminate the loop (and the program). The messages come from the user interface (the keyboard and the mouse, for instance), from messages sent by the system to the windows, from messages sent by the windows to the system, and from messages sent from one window to another.
Meanwhile, the created windows are gobbling up all the messages sent to them and taking the appropriate actions. Each window has a routine (called a window procedure) that processes messages. If window procedures were written in Visual Basic (and now they can be), a typical one might look like this:
Function WindowProc(ByVal hWnd As Long, ByVal iMessage As Long, _
ByVal wParam As Long, lParam As Long) As Long
‘ Set default return value
WindowProc = 0
‘ Handle messages
Select Case iMessage
Case WM_DOSOMETHING
DoIt “Whatever it does", wParam, lParam
Case WM_ASKSOMETHING
WindowProc = CheckIt(“Tell me, please", wParam, lParam)
Case Else
‘ Call default window procedure
WindowProc = DefWindowProc(hWnd, iMessage, wParam, lParam)
End Select
End Function
Every form and control in your program (don’t confuse me with exceptions) has one of these window procedures. Windows and Visual Basic communicate with them using the SendMessage function, and you can use it, too.