Keyboard Events and Mouse Events
When user presses a key on the keyboard, Visual Basic generates a few events. These events allow user to know which key is exactly pressed. Keyboard events occur for the controls that can receive input (have focus).
The following are the keyboard events available in Visual Basic:
When does it occur?
|KeyDown||When user presses the key on keyboard.|
|KeyUp||When user releases the key on keyboard.|
|KeyAscii||When user presses and releases an ANSI key.|
Table 8.1: Keyboard events
KeyPreview property of Form
If the KeyPreview property of the form is set to True, the form receives keyboard events before controls on the form receive the events. This is useful when you want to have a global keyboard handler for the form.
The following section will discuss all the details related to the three keyboard events mentioned in table 8.1.
KeyDown and KeyUp events
Keydown event occurs when user has pressed a key from keyboard. KeyUp event occurs when user releases a key that he has pressed earlier. That means every KeyDown event is followed by a KeyUp event.
These events occur for all types of keys including special keys like F1 and Home key. The following are parameters for these two events.
|KeyCode||A key code is the code of the key pressed. Each key on the keyboard has a code. You can use constants such as vbKeyF1 (the F1 key) to know which key on the keyboard is actually pressed by user.|
|Shift||An integer that corresponds to the state of the SHIFT, CTRL, and ALT keys at the time of the event. Please see the section “Knowing status of control key” for details on this.|
Table 8.2: Parameters of KeyDown and KeyUp events.
Knowing the status of control keys
It is possible to know which of the three control keys – SHIFT, CTRL, and ALT – are pressed at the time of pressing a key using Shift parameter of KeyDown and KeyUp events.
Shift parameter is an integer parameter with first three bits containing the status of these three control keys. Depending upon which keys are pressed the corresponding bits will be set. The bit and the corresponding key will be:
Note: You need not directly deal with bit number. You always use constants to check for the corresponding key.
To test whether shift key is pressed, enter:
If (Shift and vbCtrlMask) <> 0 then
‘ shift key is pressed
To check whether user has pressed CTRL + F1, enter:
If keycode = vbkeyF1 and ( Shift And vbCtrlMask) <> 0 then
‘ user has pressed Ctrl + f 1
keyDown and KeyUp events will not occur when user presses:
- The Enter key if the form has a CommandButton control with the Default property set to True.
- The Esc key if the form has a CommandButton control with the Cancel property set to True.
- The Tab
Note: KeyDown and KeyUp events are generally used to trap extended keys such as function key and arrow keys.
Keypress event occurs when user presses and releases a key. This event occurs only when user presses one of the ANSI keys such as alphabets, digits etc. This event doesn’t occur when user presses arrow keys, function keys etc.
KeyPress event has a single parameter, KeyAscii, which contains the ASCII code of the key that is pressed.
Note: You can ignore the character by setting KeyAscii parameter to 0.
Sample Application Using Keyboard Events
Now let us develop a small demo application to understand how to use keyboard events. This application contains a textbox into which user enters a code. By default, whatever user enters is converted to upper case and digits are not allowed. However, user can select to convert subsequently entered characters to any case and also choose to allow digits by checking Allow Digits checkbox. See figure 8.1, for user interface.
Figure 8.1: Sample application at runtime.
Let us take the required steps to create the project, create user interface, and change properties.
- Select File->New Project and select Standard Exe type
- Place the control as shown in figure 8.1 on the form.
- Change the properties as follows:
|Form1||Caption||Keyboard Events Demo|
Writing code for KeyPress Event
As we have to convert the entered text to either of the cases and disallow digits, if Allow Digits check box is unchecked, the right event for this is KeyPress event. Here is the code for KeyPress event of Text1.
Private Sub Text1_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case 48 To 57
‘ ignore if Allow Digits is unchecked
If chkallowdigits.Value = 0 Then
KeyAscii = 0 ‘ ignore
Case 65 To 90:
‘check whether lower case is selected
If optlower.Value Then
keyascii = KeyAscii + 32 ‘ convert to lower
Case 97 To 122:
‘check whether upper case is selected
If optupper.Value Then
KeyAscii = KeyAscii – 32 ‘ convert to upper
Listing 8.1: Code for KeyPress event.
In the above code, we check whether the key is a digit, or an upper case letter, or a lower case letter using ASCII code of the entered key.
The ASCII codes are as follows:
Letters A to Z 65 to 90
Letters a to z 97 to 122
Digits 0 to 9 48 to 57
Next we will understand mouse events.
Mouse events occur when user presses and releases mouse buttons. The following are the events related to mouse.
When does it occur?
|Click||When user presses and releases a mouse button.|
|Dblclick||When user presses and releases and again presses and releases a mouse button.|
|MouseDown||When user presses a mouse button.|
|MouseUp||When user releases a mouse button.|
|MouseMove||When user moves mouse pointer.|
Table 8.3: Mouse events.
Click and Dblclick event do not have any parameters. It is not possible to know which button is pressed and the position of mouse pointer at the time of click.
MouseDown, MouseUp and MouseMove events give the following information:
- The position of mouse pointer on the object at the time of user pressing a mouse button
- Which button is pressed – Left, Right or Middle.
- Which of the control keys, such as SHIFT, CTRL, and ALT, are pressed along with mouse button.
The following are the parameter of MouseDown, MouseUp and MouseMove events.
|Button||Contains a value indicating which button is pressed. The values are:
1 – left, 2 – Right, 4 – Middle.
|Shift||Contains a value indicating which control keys are held down at the time of pressing mouse button.
1 –Shift, 2 – Ctrl, 4 – Alt.
|x, y||The coordinates of the location where mouse pointer was at the time of click.|
Table 8.4: Parameters of MouseDown, MouseUp and MouseMove events
Note: The Button argument for MouseDown and MouseUp differs from the button argument used for MouseMove. For MouseDown and MouseUp, the button argument indicates exactly one button per event, whereas for MouseMove, it indicates the current state of all buttons.
Sample Application using Mouse Events
The following program allows user to draw lines as you drag the mouse pointer. Here is the list of options available in this program.
- You can draw as you move mouse pointer by holding down the left button.
- You can draw a line by connecting two points, Where points are marked with right mouse button.
- You can clear the form by holding down Shift key and pressing left mouse button.
Steps to create application
Here are the steps required to create the application.
- Select File-> New Project and select Standard Exe as the project type.
- Change the Caption of the form to Mouse Events Demo.
- Write the code for required events as show in listing .
Dim firstclick As Boolean
Dim px, py
Private Sub Form_Load()
firstclick = True
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Static x1, y1
‘shift click – clear the form
If Button = 1 And Shift = 1 Then
‘ if right button is pressed for the first time remember the
‘ coordinates of the point
If Button = 2 Then
If firstclick Then
x1 = X
y1 = Y
firstclick = False ‘ next click will not be first click
‘ This is second click so draw a line connecting first click
‘ point and current point
Line (x1, y1)-(X, Y)
firstclick = True ‘ next click will be first click
‘ if left button is pressed remember coordinates of the point where
‘ mouse button has gone down so that these coordinates can be used
‘ in MouseMove event
ElseIf Button = 1 Then
px = X
py = Y
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
‘ if user is moving mouse pointer by holding down left button
If Button = 1 Then
Line (px, py)-(X, Y)
‘ current point becomes previous point for the next event
px = X
py = Y
Listing 8.2: Code for Mouse events in sample application
Run the above project and test whether it is doing what it is supposed to do.
- Press F5 to run the project.
- First take the mouse pointer to the point from where you want to draw a line and click on right button.
- Then take the mouse pointer to the ending point and again click on right button to draw a line connecting first point with the second point. See figure 8.2.
FirstCilck is a variable that is used to know whether the click is first click or second click. It is set to false by default. It is set to true after form encounters the first click and again set to false at second click.
- Now, test dragging mouse pointer to draw a line. Whenever you move the mouse pointer by holding left button a continuous line is to be drawn as you move the mouse pointer. Test it by dragging the mouse pointer to draw your name (See figure 8.3).
- To clear whatever is on the form, press Shift + left button of mouse
Drag and Drop
Drag and drop is an interface. It allows users to drag and drop a control to another control. Dropping control invokes an action. For example, in windows explorer when you drag a set of files from one directory and drop them on another directory, all the selected files will be moved (or copied, if Ctrl key is pressed) to the directory on which the files are dropped.
Figure 8.2: Form after a line is drawn using right button
Figure 8.3: Form after name is drawn by dragging mouse pointer.
The control that is being dragged is called Source, and the object on which the Control is dropped is called as Target.
The following are various properties, methods and events related to drag and drop.
|Property||Dragmode||Specifies whether control is in manual drag mode or in automatic drag mode. Please see the following section on drag modes.|
|Property||Dragicon||Specifies the icon to be used as the mouse pointer during drag and drop operation.|
|Method||Drag||Begins, ends, or cancels a drag operation.|
|Event||Dragdrop||This event occurs when a source control is dropped on the target. This event occurs on target.|
|Event||DragOver||Occurs on target when the dragging process is in progress.|
Table 8.5: Properties, Methods, and Events related to Drag-and-drop.
Manual vs. Automatic drag mode
A control may be in either manual drag mode or automatic drag mode. In manual drag mode, program has to initiate dragging process by calling drag method. Whereas in automatic drag mode, whenever user clicks on the control, drag process is initiated.
Set DragMode property of the Control to 0 for manual drag mode or 1 for automatic drag mode.
Drag method is used to initiate, cancel or end drag operation. Drag method is used to initiate drag operation only when control is in manual drag mode (DragMode set to 0).
The following are the valid actions.
|0||VbCancel||Cancels drag operation.|
|1||VbBeginDrag||Initiate drag operation.|
|2||VbEndDrag||Ends drag operation and drops the Control.|
Note : Change the icon used as mousepointer during dragging process using DragIcon property before dragging is initiated.
Events related to Drag and drop
During drag-and-drop operation DragOver and DragDrop events occur. Both events occur on target Control. DragOver event occurs when dragging is in progress. DragDrop event occurs after the Control is dropped. Both events allow you to access the source control through source parameter
The following are the common parameters of DragOver and DragDrop events. DragOver has one extra parameter – State.
|Source||Refers to the control that is being dragged. You can access the properties and methods of source control, for example : Source.Picture|
|X, y||The x and y coordinates of mouse pointer within target control.|
|State||Indicates the transition state of the control being dragged in relation to a target control. The following are valid values:
0 = Enter (source control is being dragged within the range of a target).
1 = Leave (source control is being dragged out of the range of a target).
2 = Over (source control has moved from one position in the target to another).
Table 8.6 : Parameters of Drag and Drop event procedures.
Sample Application using Drag and Drop
Let us develop a small application using drag and drop. The aim of this application is to illustrate how to use various methods, properties and events related to drag and drop.
The application contains four image controls. Three of them will contain images of the default size and one will stretch the image. When user drags any of the three images into fourth image and drops it, the dropped image will be displayed in enlarged mode. To get an idea about how it will be, see figure 8.4.
Figure 8.4: After second image is dropped on to fourth image, where it is enlarged
The following are the steps to be taken to develop this sample application.
- Start a new project using File->New Project and select Standard EXE as the type of the project.
- Place four image controls on the form and change the properties as follows.
|Form1||Caption||Drag and Drop Example|
Note: The picture that is placed in Image control must be an Icon. Because the same picture is used for DragIcon property, Which can take only an Icon.
Write the following code. The code consists of MouseDown event for first three image controls and DragDrop event for fourth image.
Private Sub Image1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Image1.DragIcon = Image1.Picture
Private Sub Image2_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Image2.DragIcon = Image2.Picture
Private Sub Image3_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Image3.DragIcon = Image3.Picture
Private Sub Image4_DragDrop(Source As Control, X As Single, Y As Single)
Image4.Picture = Source.Picture
Listing 8.3: Code for Drag and Drop sample application.
- Run the application to understand how it implemented drag and drop. To run press F5.
- Click on any of the first three images and start moving the mouse pointer by holding down left button (dragging).
- Along with mouse pointer the picture of the image control that you are dragging is moved. This is because we changed DragIcon property to the icon in Image control before dragging process starts.
- Move the mouse pointer to Image4 and drop it there. At this stage you should see the enlarged image displayed in fourth image control (see figure 8.4).
Using DragOver event
You can use DragOver event of Image4 to display a different icon when control enters into it to inform the user that the pointer has reached the place where the control can be dropped. This could be done by changing DragIcon property of the source control when State parameter is 0 (enter). Again DragIcon can be reset when control goes out of image4. The sample code is shown in listing 8.4.
Private Sub Image4_DragOver(Source As Control, X As Single, Y As Single, State As Integer)
‘ if entering into control then change dragicon to icon
‘ that indicates potential area to drop
If State = 0 Then ‘replace potential.ico with an Icon that you want ‘ to use.
Source.DragIcon = LoadPicture(“potential.ico”)
‘ if leaving then reset control’s dragicon
ElseIf State = 1 Then
Source.DragIcon = Source.Picture
Listing 8.4: Code to change mouse pointer when control enters and leaves target.
Using a control array to simplify code
A control array is an array of controls. A control array is used when we have to write more or less the same code for a group of controls of the same type. The sample application that we have developed for drag and drop, is one of the candidates for control array. As you can see, the code that we wrote for first three images is same except the name of the control. So by using a control array we can write the same code just for once, instead of three times.
The concept of control array is same as the concept of menu array, Which we have seen in chapter 7. A control array is a collection of controls with the same name but with different values for Index property of the controls. Whenever an event occurs at any of the controls in the control array, only one event procedure is fired; that is of the control array and not individual controls.
The event procedures of control array contain one extra parameter, Index, that contains the index value of the control at which event has occurred.
To create a control for three images, take the following steps:
- Change the Name property of all three images (Image1, Image2 and Image3) to Images.
- Change the Index of first image control to 0, second image control to 1, and third image control to 2.
- Write the code for MouseDown event of control array – Images, as shown in listing 8.5.
Private Sub Images_MouseDown(Index as Integer, Button As Integer, Shift As Integer, X As Single, Y As Single)
Images(index).DragIcon = Images(index).Picture
Listing 8.5: Code for MouseDown event of the control array.
Images (index) refers to the control that initiated the event. So we use Drag method of that control to start dragging.
That’s all. No more changes are required. Code for DragDrop and DragOver events will remain the same. If you run the application, it will do the same job as before. But it is more efficient because we have only one event procedure for three images instead of three separate event procedures.