User Form with Movable Controls

I'm not sure of the practical significance of this technique, but the example in this section will help you understand mouse-related events. The UserForm shown in Figure 15-13 contains three Image controls. The user can use the mouse to drag these images around in the dialog box.

Figure 15-13: The three Image controls can be dragged and rearranged by using the mouse.

CD- This example is available on the companion CD-ROM. The file is named % move R°M controls.xlsm.

Figure 15-13: The three Image controls can be dragged and rearranged by using the mouse.

CD- This example is available on the companion CD-ROM. The file is named % move R°M controls.xlsm.

Each of the Image controls has two associated event procedures: MouseDown and MouseMove. The event procedures for the Imagel control are shown here (the others are identical except for the control names).

Private Sub Image1_MouseDown(ByVal Button As Integer, _

ByVal Shift As Integer, ByVal x As Single, ByVal Y As Single) ' Starting position when button is pressed OldX = x OldY = Y Imagel.ZOrder 0 End Sub

Private Sub Image1_MouseMove(ByVal Button As Integer, _

ByVal Shift As Integer, ByVal x As Single, ByVal Y As Single) ' Move the image

If Button = 1 Then

Imagel.Left = Imagel.Left + (X - OldX) Imagel.Top = Imagel.Top + (Y - OldY) End If End Sub

When the mouse button is pressed, the MouseDown event occurs, and the * and Y positions of the mouse pointer are stored. Two public variables are used to keep track of the original position of the controls: OldX and OldY. This procedure also changes the ZOrder property, which puts the image "on top" of the others.

When the mouse is being moved, the MouseMove event occurs repeatedly. The event procedure checks the mouse button. If the Button argument is 1, it means that the left mouse button is depressed. If so, then the Image control is shifted relative to its old position.

Also, notice that the mouse pointer changes when it's over an image. That's because the MousePointer property is set to 15 - fmMousePointerSizeAll. This mouse pointer style is commonly used to indicate that something can be moved.

4 PREV

0 -1

Post a comment