Visual Basic Reference

Drag Method Example

This example uses the Drag method to drag the filename of a bitmap (.bmp) file to a picture box where the bitmap is displayed. To try this example, paste all of the code into the Declarations section of a form that contains DriveListBox, DirListBox, FileListBox, PictureBox, and Label controls. Use the default names for all of the controls. Size and position all controls so they can be easily seen and used. The size and position of the label is unimportant because it's changed at run time. When the program begins, you can browse your file system and load any bitmaps. Once you've located a bitmap that you want to display, click the filename of that bitmap, and drag it to the picture box.

  Private Sub Form_Load ()
   Picture1.AutoSize = -1   ' Turn on AutoSize.
   Label1.Visible = 0   ' Make the label invisible.
   File1.Pattern = "*.BMP; *.ICO; *.WMF"   ' Set file patterns.
End Sub

Private Sub Dir1_Change ()   ' Any change in Dir1
   File1.Path = Dir1.Path   ' is reflected in File1.
End Sub

Private Sub Drive1_Change ()   ' Any change in Drive1
   Dir1.Path = Drive1.Drive   ' is reflected in Dir1.
End Sub

Private Sub File1_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)
   Dim DY   ' Declare variable.
   DY = TextHeight("A")   ' Get height of one line.
   Label1.Move File1.Left, File1.Top + Y - DY /2, File1.Width, DY
   Label1.Drag   ' Drag label outline.
End Sub

Private Sub Dir1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)
   ' Change pointer to no drop.
   If State = 0 Then Source.MousePointer = 12
   ' Use default mouse pointer.
   If State = 1 Then Source.MousePointer = 0
End Sub

Private Sub Drive1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)
   ' Change pointer to no drop.
   If State = 0 Then Source.MousePointer = 12
   ' Use default mouse pointer.
   If State = 1 Then Source.MousePointer = 0
End Sub

Private Sub Form_DragOver (Source As Control, X As Single, Y As Single, State As Integer)
   ' Change pointer to no drop.
   If State = 0 Then Source.MousePointer = 12   
   ' Use default mouse pointer.
   If State = 1 Then Source.MousePointer = 0   
End Sub

Private Sub File1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)
   On Error Resume Next
   If State = 0 And Right$(File1.Filename,4) = ".ICO" Then
      Label1.DragIcon = LoadPicture(File1.Path + "\" + File1.Filename)
   If Err Then MsgBox "The icon file can't be loaded."
   ElseIf State = 1 Then
      Label1.DragIcon = LoadPicture ()   ' Use no drag icon.
   End If
End Sub

Private Sub Picture1_DragDrop (Source As Control, X As Single, Y As Single)
   On Error Resume Next
   Picture1.Picture = LoadPicture(File1.Path + "\" + File1.Filename)
   If Err Then MsgBox "The picture file can't be loaded."
End Sub