Tip 32: Creating Custom Cursors (Mouse Pointers)

Created: March 1, 1995

Abstract

When you are designing an application, Visual Basic® lets you assign the MousePointer property of many controls to one of the twelve predefined mouse cursors. Typically you would change the MousePointer property of a control to tell your program's user that some kind of action has been invoked. For example, the hourglass cursor is used to indicate the passage of time. At other times, you may just want to inform the user that she or he positioned the mouse pointer over a specific control, such as a File List Box. To do this, you would simply change the MousePointer property of that control at the appropriate time in your Visual Basic application.

However, you may want to display a cursor shape not included in the twelve predefined shapes. This article explains how you can create a different mouse pointer (cursor), even for controls that do not have a MousePointer property.

Changing the Cursor (Mouse Pointer)

To change the cursor (mouse pointer) to a different shape within your Visual Basic® application, you add code to change the MouseMove and DragOver events for the control you want to monitor.

The MouseMove event contains code that triggers a Drag method for the control. This in turn displays the new mouse pointer when the cursor is moved over the selected control. When the mouse pointer is moved off the control, the DragOver event is triggered. In your Visual Basic program, you reset the Drag property so that the original mouse pointer is again displayed.

Example Program

The following program changes the mouse pointer to a different shape when the pointer is moved over a File List Box control.

  1. Start a new project in Visual Basic. Form1 is created by default.

  2. Add a File List Box control to Form1. File1 is created by default.

  3. Set the DragIcon property of the File1 control to an .ICO file of your choice.

  4. Add the following code to the MouseMove event for File1:
    Sub File1_MouseMove(Button As Integer, Shift As Integer, X As Single,
                        Y As Single)
        File1.Drag 1       'icon on
    End Sub
    

    Note that the "Sub File1_MouseMove" line must be typed as a single line of code.

  5. Add the following code to the DragOver event for Form1:
    Sub Form_DragOver(Source As Control, X As Single, Y As Single, State As Integer) 
        File1.Drag 0       'icon off
    End Sub
    

Run this demonstration program by pressing the F5 function key. Whenever you move the mouse pointer over the File List Box control, the program will display your selected .ICO file as the default mouse pointer. Move the mouse pointer off the control, and the cursor changes back to its default shape.