Messages and Events of Windows Controls


Controls Messages



You can add Windows controls to a work area or to a form to help a user interact your application. When a control is used, it must communicate with the operating system. For example, when a user clicks, the object that was clicked must inform the operating system that it has been clicked. This is the case for every control used in an application. Because a typical application can involve many controls, a mechanism was designed to manage the occurrence of actions.

To communicate its intention to the operating system, a Windows control must compose a message and send it (to the operating system).

The Parts of a Message

In order to make a message clear, the control that wants to send it must provide three important pieces of information:

  • WHO sent the message? When a control sends a message, it must identify itself because there can be many controls sending different messages at the same time. The operating system will need to know where the message came from. This is one of the reasons why every control must have a name. Also because each message is particular to the control that sent it, the message is considered a private matter.
    Based on this, the code of a message starts with Private Sub, followed by the name of the control that is sending the message:
    Private Sub ControlName
  • WHAT message? When a control is sending a message, it must specify the type of message. A control can be able to send various types of messages. For example, when a control gets clicked, it sends a Click message. If the same control receives focus but you press a key, the control sends a keyboard-related message. When the mouse passes over that same control, its sends a different type of message.
    Every message a control can send has a name. To see the types of message available for a particular control, open Microsoft Visual Basic. In the Object combo box, select the name of the control. Then, click the arrow of the Procedure combo box:
    Code Editor
    By convention, the name of the message follows the name of the control but they are separated with an underscore. It would appear as:
    Private Sub ControlName_Push
  • Arguments: An argument is additional information needed to process a message. When a control sends a message, it may need to accompany it with some information. For example, if you position the mouse on a control and click, the operating system may need to know what button of the mouse was used to click. On the other hand, if you select an object and start dragging, the operating system may need to know if a key such as Shift or Ctrl was held down while you were dragging.
    An additional piece of information that the control provides is provided as an argument. While some messages may need to provide only one piece of information, some messages would require more than one argument. Some other messages don't need any additional information at all: the name of the message would completely indicate how the message must be processed.
    The arguments of a message are provided in parentheses. They would appear as:
    Private Sub ControlName_Push(Argument1, Argument2, Argument_n)

After specifying the message, you can type code that tells the operating system what to do to process the message. To indicate the end of the code that relates to a message, type End Sub

Private Sub ControlName_Push(Argument1, Argument2, Argument_n)
End Sub

As mentioned earlier, a message must be composed and sent. The action of sending a message is called an event. It is also said that the controls "fires" an event. Based on the above descriptions, to compose and send a message, in the Object combo box, you can select the name of the control that will send the message, then select the desired message in the Procedure combo box. When you do this, Microsoft Visual Basic will write the first line that specifies the name of the control, the name of the event, its arguments if any, and would write End Sub for you. You can then enter the necessary code between those two lines.

Most Windows control have a special event referred to as the default. This is the even that is the most obvious that the control can fire. For example, when you think of a button, the first action that comes to mind is Click. For this reason, Click is the default event of a button. If you add a control to a work area or to a form and double-click the control, its default event would be invoked and the skeleton of that event would be written in the corresponding module. If you don't want to use that event or to fires another event for the same control, you can simply select the event in the Procedure combo box.

Practical LearningPractical Learning: Introducing Messages and Events

  1. Start Microsoft Excel
  2. Save the document as Messages
  3. To open Microsoft Visual Basic, on the Ribbon, click Developer and, in the Code section, click Visual Basic
  4. To create a form, on the Standard toolbar, click the Insert UserForm button Insert UserForm
  5. Right-click the form and click Properties
  6. In the Properties window, click (Name) and type frmPayroll
  7. On the Toolbox, click the TextBox and click the form
  8. Complete the design of the form as follows:
    Employee Payroll
    Control Name Caption Other Properties
    Label lblHourlySalary Hourly Salary:  
    TextBox txtHourlySalary   TextAlign: 3 - frmTextAlignRight
    Label lblWeeklyHours Weekly Hours:  
    TextBox txtWeeklyHours   TextAlign: 3 - frmTextAlignRight
    CommandButton cmdCalculate    
    Label lblWeeklySalary Weekly Salary:  
    TextBox txtWeeklySalary   TextAlign: 3 - frmTextAlignRight
  9. Save the file

Common Events of Windows Controls



To interact with the computer, one of the most usually performed actions is to click. The mouse is equipped with two buttons. The most clicked button is the left one.

Because the action simply consists of clicking, when you press this button, a simple event, called Click is sent or fired. When you press the (left) button on the mouse, the mouse pointer is usually on a Windows control. Based on this, the control that is clicked "owns" the event and must manage it. Therefore, no detailed information is provided as part of the event. The operating system believes that the control that fired the event knows what to do. For this reason, whenever you decide to code an OnClick event, you should make sure you know what control sent or fired the event. This is (one of) the most common events of Windows controls.

Practical LearningPractical Learning: Generating a Click Event

  1. To generate a Click event for the button, on the form, double-click the Calculate button and notice that its Click event has been generated
  2. Implement the Click event as follows:
    Private Sub cmdCalculate_Click()
        Dim HourlySalary As Currency
        Dim WeeklyHours As Double
        Dim WeeklySalary As Currency
        HourlySalary = CCur(txtHourlySalary.Text)
        WeeklyHours = CDbl(txtWeeklyHours.Text)
        WeeklySalary = HourlySalary * WeeklyHours
        txtWeeklySalary.Text = CStr(WeeklySalary)
    End Sub
  3. To test the form, on the main menu of Visual Basic, click Run -> Run Sub/UserForm
  4. Enter 15.48 in the Hourly Salary and 36.50 in the Weekly Hours text boxes and click Calculate
    Employee Payroll
  5. Close the form


Another common action you perform on a control may consist of double-clicking it. This action causes the control to fire an event known as DblClick.

Practical LearningPractical Learning: Generating a Double-Click Event

  1. On the form, right-click the Calculate button and click View Code
  2. In the Object combo box, select UserForm
  3. In the Procedure combo box, select DblCllck and notice the structure of the event:
    Private Sub UserForm_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
        lblHourlySalary.BackColor = vbBlue
        lblWeeklyHours.BackColor = vbBlue
        lblWeeklySalary.BackColor = vbBlue
        lblHourlySalary.ForeColor = vbWhite
        lblWeeklyHours.ForeColor = vbWhite
        lblWeeklySalary.ForeColor = vbWhite
        BackColor = vbBlue
    End Sub
  4. To test the form, on the main menu of Visual Basic, click Run -> Run Sub/UserForm
  5. Double-click the form
    Employee Payroll
  6. Close the form

Entering a Control

Just as an application can have many forms, a form can be equipped with various controls. Such is the case for any data entry form. On a form that is equipped with many controls, only one control can be changed at a time. Such a control is said to have focus. To give focus to a control, you can click it or can keep pressing Tab until the desired control indicates that it has focus. In a form with many controls, the control that has focus may display a caret or a dotted line around its selection or its caption.

When a form or a control receives focus, it fires the Enter event. We mentioned that a user can give focus to a control by clicking it. If the control is text-based, then a caret blinking in the control indicates that the control has focus.

The Enter event does not take any argument:

Private Sub TextBox1_Enter()

End Sub

Exiting a Control

After using a control, you can switch to another control either by clicking another or by pressing Tab. This causes the focus to shift from the current control to another. If the focus shifts to another control, the control that had focus fires an Exit event.

The Exit event takes one argument, :

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Keyboard Events

Word processing consists of manipulating text and characters on your computer until you get the fantastic result you long for. To display these characters, you press some keys on your keyboard. If the application is configured to receive text, your pressing actions will display characters on the screen. The keyboard is also used to perform various other actions such as accepting what a dialog box displays or dismissing it.

When you press the keys on a keyboard, the control in which the characters are being typed sends one or more messages to the operating system. There are three main events that Microsoft Windows associates to the keyboard.

KeyDown: When you press a key on the keyboard, an event called KeyDown is fired. The KeyDown event takes two arguments:

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
			     ByVal Shift As Integer)

End Sub

KeyUp: When you release a key that was pressed, an event called KeyUp fires.
These two previous events apply to almost any key on the keyboard, even if you are not typing; that is, even if the result of pressing a key did not display a character on the document.

Private Sub TextBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, _
			   ByVal Shift As Integer)

End Sub

KeyPress: The KeyPress event fires if the key you pressed is recognized as a character key; that is, a key that would result in displaying a character in a document.

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

End Sub

Some keys on the keyboard don't display anything on a document. Instead, they perform (only) an action. Examples of such keys are Enter, Tab, Esc. Therefore, if you mean to find out what key you pressed, use the KeyDown event instead of the KeyPress event.


Pressing a Mouse Button Down

A mouse is equipped with buttons, usually two, that you press to request an action. Compared to the keyboard, the mouse claims many more events that are directly or indirectly related to pressing one of its buttons.

When you press one of the buttons on the mouse, an event, called MouseDown fires. This event carries enough information as three arguments. 

Private Sub txtFirstName_MouseDown(Button As Integer, Shift As Integer,
      X As Single, Y As Single)

End Sub
  • The operating system needs to know what button was pressed; this is represented as the left or the right button. The left button is known as vbLeftButton. The right button is referenced as vbRightButton. If the mouse is equipped with a middle button, it would vbMiddleButton. In reality, these buttons have (constant) numeric values of 0, 1, and 2 respectively.
  • Secondly, the operating system needs to know whether a special key, Shift, Ctrl, or Alt, was pressed. These buttons are called vbShiftMask, vbCtrlMask, and vbAltMask respectively. In reality, they are represented with 1, 2, and 4 respectively.
  • Lastly, the operating system needs to know the screen coordinates of the mouse pointer, that is, the coordinates of the point where the mouse landed. X represents the distance from the top left corner of the parent to the mouse. Y represents the vertical measure of the point from the top-left corner down.

Releasing a Mouse Button

When you release a button that was pressed on the mouse, a new event fires. This event is called MouseUp. It provides the same types of information as the MouseDown event:

Private Sub txtFirstName_MouseUp(Button As Integer, Shift As Integer,
      				 X As Single, Y As Single)

End Sub

Moving the Mouse

The MouseMove event is sent while you are moving the mouse on a control. It provides the same pieces of information as the MouseDown and the MouseUp events:

Private Sub txtFirstName_MouseMove(Button As Integer, Shift As Integer,
      				   X As Single, Y As Single)

End Sub

Changing Text

One of the most important messages of a text box occurs when its content changes. That is, when the text it has is deleted, added to, or edited. When you click in a text box control and start typing it or change its text, the control fires a Change event.

Practical Learning Practical Learning: Using the Change Event of a Text Box

  1. To add a new form, on the main menu of Microsoft Visual Basic, click Insert -> UserForm
  2. In the Properties window, change its (Name) to frmEmployeeInformation
  3. Design the form as follows:
    Employee Information
    Control Name Caption
    Label First Name:
    TextBox txtFirstName  
    Label   Last Name:
    TextBox txtLastName  
    Label   Full Name:
    TextBox txtFullName  
  4. Double-click the top text box and implement its Change event as follows:
    Private Sub txtFirstName_Change()
        Dim FirstName As String
        Dim LastName As String
        Dim FullName As String
        FirstName = txtFirstName.Text
        LastName = txtLastName.Text
        FullName = FirstName & " " & LastName
        txtFullName.Text = FullName
    End Sub
  5. In the Object combo box, select txtLastName and implement its Change event as follows:
    Private Sub txtLastName_Change()
        Dim FirstName As String
        Dim LastName As String
        Dim FullName As String
        FirstName = txtFirstName.Text
        LastName = txtLastName.Text
        FullName = FirstName & " " & LastName
        txtFullName.Text = FullName
    End Sub
  6. To test the form, on the main menu of Visual Basic, click Run -> Run Sub/UserForm
  7. Click the top text box, type Julienne and press Tab
  8. In the other text box, start typing Pal and notice that the Full Name text box is changing
    Employee Information
  9. Complete it with Palace and close the form

Previous Copyright © 2004-2009 FunctionX, Inc. Next