Search code examples
vb.netdrag-and-drop.net-4.5

How to draw control while is moved in a Drag-and-drop event


In Vb.net, through Drag and Drop events, a control (button) is moved from a Panel to another Panel.

Is there any way or option to draw the control (button) while is being moved by cursor? Now I have only reached to change cursor shape, and when the action of Drag and Drop is finished, the control is drawn in its new panel parent.

Thanks in advance.

Edit: Added code

public Sub New()
    InitializeComponent()
    '….
    Panel1.AllowDrop = True
    Panel2.AllowDrop = True

    AddHandler Panel1.DragEnter, AddressOf panel_DragEnter
    AddHandler Panel2.DragEnter, AddressOf panel_DragEnter

    AddHandler Panel1.DragDrop, AddressOf panel_DragDrop
    AddHandler Panel2.DragDrop, AddressOf panel_DragDrop

    AddHandler Button1.MouseDown, AddressOf button1_MouseDown

    Panel1.Controls.Add(Button1)

 End Sub

 Sub button1_MouseDown (ByVal sender As Object, e As MouseEventArgs)
     sender.dodragdrop(sender, DragDropEffects.Move)
 End Sub

 Sub panel_DragEnter (ByVal sender As Object, e As DragEventArgs)
     e.Effect = DragDropEffects.Move
 End Sub

 Sub panel_DragDrop (ByVal sender As Object, e As DragEventArgs)
     Dim aButton As Button = DirectCast(e.Data.GetData(GetType(Button)), Button)
     Dim aPanel As Panel = DirectCast(sender, Panel)

     button.Parent = aPanel
 End Sub

Solution

  • You have to create a bmp/cursor on the MouseDown event. Then, in the GiveFeedback event, you have to disable UseDefaultCursors so that it doesn't change back to the default cursor as soon as they move the mouse. Then, in the DragOver event, you set your cursor object (created in MouseDown) to be the current cursor. This will also serve to reapply your custom cursor if the current cursor got reset somehow to another cursor. This would happen if you moved your cursor off of the designated dragging area and it changed to the "can't drop it here" icon.

    You have to setup these Subs to Handle the appropriate events on the corresponding controls. Also, when setting up the bitmap, "c" is the control in question that it needs to draw. This may or may not be the sender, depending on your circumstances, so it's up to you to determine which control you want drawn at that time.

    Private cur As Cursor
    
    Private Sub GiveFeedback(sender As Object, e As GiveFeedbackEventArgs)
        e.UseDefaultCursors = False
    End Sub
    
    Private Sub MouseDown(sender As Object, e As MouseEventArgs)
        Dim bmp As Bitmap = New Bitmap(c.Width, c.Height)
        c.DrawToBitmap(bmp, New Rectangle(Point.Empty, bmp.Size))
        cur = New Cursor(bmp.GetHicon())
    End Sub
    
    Private Sub DragOver(sender As Object, e As DragEventArgs)
        If Cursor.Current <> cur Then Cursor.Current = cur
    End Sub