Page 1 of 1

Dragging - moving controls

Posted: Thu Aug 20, 2009 1:16 am
by CodenStuff
Hello,

This little snip will show you how to drag and move a control around your form using the mouse.

Here is the code:

Make public variables called:
Public capt = 0
Public a
Public b


Place the following codes in your chosen controls mouse events:

MouseUp
Code: Select all
YourControl.Location = New Point(YourControl.Location.X + (e.X - a), YourControl.Location.Y + (e.Y - b))
capt = 0
MouseDown
Code: Select all
 a = e.X
b = e.Y
capt = 1
MouseMove
Code: Select all
If capt = 1 Then
YourControl.Location = New Point(YourControl.Location.X + (e.X - a), YourControl.Location.Y + (e.Y - b))
End If

Replace the word 'Yourcontrol' with the name of your control. So for example if I wanted to drag and move and picturebox control the code would look like this:
Code: Select all
Private Sub PictureBox1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
        PictureBox1.Location = New Point(PictureBox1.Location.X + (e.X - a), PictureBox1.Location.Y + (e.Y - b))
        capt = 0
    End Sub
    Private Sub PictureBox1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
        a = e.X
        b = e.Y
        capt = 1
    End Sub
    Private Sub PictureBox1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
        If capt = 1 Then
            PictureBox1.Location = New Point(PictureBox1.Location.X + (e.X - a), PictureBox1.Location.Y + (e.Y - b))
        End If
    End Sub
Happy dragging :D

Re: Dragging - moving controls

Posted: Fri May 21, 2010 1:56 pm
by hungryhounduk
Hi Codenstuff
ok i followed the Tutorial Above, but i get "a is not declared" and the "b" is the same

am I missing something :lol:

Chris

Re: Dragging - moving controls

Posted: Fri May 21, 2010 2:50 pm
by CodenStuff
Hello,

Errm oh yes lol. Under Public capt=0 Put:
Code: Select all
Public a
Public b
I forgot that bit :D

Re: Dragging - moving controls

Posted: Fri May 21, 2010 3:14 pm
by mandai
Wouldn't it be better if capt were a Boolean?

Re: Dragging - moving controls

Posted: Sat May 22, 2010 12:27 am
by CodenStuff
Hello mandai,

Well wouldnt make much difference but yes either way works cooll;

Re: Dragging - moving controls

Posted: Sat May 22, 2010 9:54 am
by hungryhounduk
Hi Codenstuff
Thanks for that, I have an idea for another Game and that is just what i am after :)

Cheers

Chris