WWW Yariv Hammer's Code Site

Friday, October 21, 2005

How-to allow user to move a control on a form.

Sometimes you may want the user to move controls on the form at run-time, same way you do it in the form's designer as a developer.
I will show a way to achieve this effect using mouse events. For the purpose of the demonstration I am using a TextBox, but you can apply this to any control with MouseDown, MouseUp and MouseMove event.
I am using VB.NET here.

The code
Drag a textBox to the form (textBox1) And add the code to the form:

Private _mouseDown As Boolean = False
Private _initialMouseX As Integer
Private _initialMouseY As Integer

Private Sub textBox1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles textBox1.MouseDown
   _mouseDown = True
   _initialMouseX = e.X
   _initialMouseY = e.Y
End Sub

Private Sub textBox1_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles textBox1.MouseUp
   _mouseDown = False
End Sub

Private Sub textBox1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles textBox1.MouseMove
   If ( Not _mouseDown) Then Return
   Dim deltaX As Integer = e.X - _initialMouseX
   Dim deltaY As Integer = e.Y - _initialMouseY
   textBox1.Left += deltaX
   textBox1.Top += deltaY
End Sub

I am using the MouseDown event to store the initial position of the mouse, and to set a flag that when the mouse will move we want the control to move with it.
I am using the MouseUp event to release the flag (When moving the mouse the control will not move).
The MouseMove event is used to actually move the control. The current coordinates of the mouse is compared to the initial position and moving the control by setting the Left and Top properties. All this only if the mouse is down of course.

In the next postI will show how to let the user resize the control using the mouse.


Post a Comment

<< Home

Feel free to use everything here. Add links to my site if you wish.

Do not copy anything to other sites without adding link to here.

All the contents of the site belong to Yariv Hammer.