Mouser coordinate [cont]

  • Thread starter Thread starter MAY
  • Start date Start date
M

MAY

hi,

how to make a button move with mouse cursor on a from when mouse down, and
stop moving when mouse up.

Thx.


MAY
 
Hi MAY,

This is simple enough, you need to handle the buttons mousedown and mousemove events.

private int startX = 0; //
private int startY = 0; // these will know the start position of the drag procedure

private void button1_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left) // store start position
{
startX = e.X;
startY = e.Y;
}
}

private void button1_MouseMove(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
// if Left button is down we have a drag
// set the buttons new position based on the difference
// between the current mouse position and the start position

button1.Location = new Point(button1.Left + (e.X-startX), button1.Top + (e.Y-startY));
}
}

Note, this code will let you drag the button outside the form, so you might want to check the move code and not accept values that are outside the parent form's boundaries.


Happy coding!
Morten Wennevik [C# MVP]
 
Thanks for your valuable reply :)

MAY


Morten Wennevik said:
Hi MAY,

This is simple enough, you need to handle the buttons mousedown and mousemove events.

private int startX = 0; //
private int startY = 0; // these will know the start position of the drag procedure

private void button1_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left) // store start position
{
startX = e.X;
startY = e.Y;
}
}

private void button1_MouseMove(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
// if Left button is down we have a drag
// set the buttons new position based on the difference
// between the current mouse position and the start position

button1.Location = new Point(button1.Left + (e.X-startX), button1.Top + (e.Y-startY));
}
}

Note, this code will let you drag the button outside the form, so you
might want to check the move code and not accept values that are outside the
parent form's boundaries.
Happy coding!
Morten Wennevik [C# MVP]
 
Back
Top