Mover y soltar controles con Drag & Drop (Visual Basic)
Visual Basic 6 noviembre 2007
‘Me ha costado cogerle el tranquillo al tema del Drag & Drop,
‘ya que los ejemplos no ayudaban mucho para lo que yo lo quería.
‘Se usan: DragOver, DragDrop, MouseDown y MouseUp.
‘El único coñazo es tener que poner código en todos los controles…
‘——————————————————————–
‘Variables a nivel del módulo
Dim DY As Single
Dim DX As Single
Private Sub CancelarDrag(Source As Control)
Source.Visible = True
Source.Drag vbCancel
End Sub
Private Sub FinalizarDrag(Source As Control, Button As Integer)
If Button = vbLeftButton Then
Source.Visible = True
Source.ZOrder
Source.Drag vbEndDrag
End If
End Sub
Private Sub IniciarDrag(Source As Control, Button As Integer, X As Single, Y As Single)
If Button = vbLeftButton Then
DX = X
DY = Y
‘Permitir la operación de Drag & Drop
Source.Drag vbBeginDrag
‘Cambiar a no visible, ya que si no, el form no detectaría que se ha soltado, si el puntero del ratón no sale del control.
Source.Visible = False
‘Comienza el espectáculo
Source.Drag
End If
End Sub
Private Sub Form_DragDrop(Source As Control, X As Single, Y As Single)
‘Si se quieren excluir algunos controles,
‘hacer aquí la comparación.
Source.Visible = True
Source.Move X – DX -60, Y – DY -60
Source.Drag vbEndDrag
Source.ZOrder
End Sub
‘En cada control poner este código:
(cambiar %Control% por el nombre apropiado)
‘
Private Sub %Control%_DragDrop(Source As Control, X As Single, Y As Single)
CancelarDrag Source
End Sub
‘
Private Sub %Control%_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
IniciarDrag %Control%, Button, X, Y
End Sub
‘
Private Sub %Control%_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
FinalizarDrag %Control%, Button
End Sub
‘
‘Se puede añadir DragOver para que muestre un icono no permitiendo que se suelte.
Posts anterior y posterior:
Posts Relacionados:
- Previo: « Mover un Form sin caption
- Siguiente: Cambiar el tamaño de un Picture usando el API de Windows (Visual Basic) »
septiembre 10th, 2009 a las 4:50 pm
Parece que no acepta restar tres números cuando se trata de datos Single. Pero ya lo corregí:
Private Sub Form_DragDrop(Source As Control, X As Single, Y As Single)
Dim ejeY, ejeX As Single
ejeX = X – 60
ejeY = Y – 60
ejeX = ejeX – DX
ejeY = ejeY – DY
Source.Visible = True
Source.Move ejeX, ejeY
Source.Drag vbEndDrag
Source.ZOrder
End Sub
Gracias por el código, es justo lo que necesitaba
agosto 31st, 2010 a las 10:25 pm
Saludos. Podría aplicar este código al VBasic de Excel ? de ser así… dónde puedo conseguir la biblioteca que maneja el Evento DragDrop ?
Muchas gracias