Vb.net – How to move an element by clicking and holding the object with the mouse

mousemovevb.net

I am working on a simple program which requires me to be able to select a picture box and move it to a new location by dragging it with my mouse. This is all the relevant code I have come up with currently. However, when I run the program it tries to move to where I want it to go then it seems to revert back to its previous location.

Edit: it is in a container. If this is of any relevance.

Variables

Dim startx As Integer
Dim starty As Integer
Dim endy As Integer
Dim endx As Integer
Dim finalx As Integer
Dim finaly As Integer
Dim mdown As Boolean
Dim valx As Boolean
Dim valy As Boolean

Code to make image move

    Private Sub picbox_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles picbox.MouseDown
        startx = MousePosition.X
        starty = MousePosition.Y
        mdown = True
        valx = False
        valy = False
    End Sub

Private Sub Main_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove End Sub Private Sub picbox_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles picbox.MouseMove 'Check if mouse=down If mdown = True Then endx = (MousePosition.X - Me.Left) endy = (MousePosition.Y - Me.Top) If valy = False Then starty = endy - sender.top valy = True End If If valx = False Then startx = endx - sender.left valx = True End If sender.left = endx - startx sender.top = endy - starty End If End Sub Private Sub picbox_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles picbox.MouseUp mdown = False valx = False valy = False End Sub

Best Answer

Remove it out of the container. That is probably what is giving you the problems as your code works perfectly for me.

Related Topic