Search code examples
c#.netwinformsmouseclick-event

How to calculate the distance that the mouse moved during click


I have this code :

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    if(chckeckbox.checked)
    {
      //the distance that the mouse made when the left click remained clicked
    }
} 

by what do I have to change the comments so that it works? in addition to that my if it already finds in an event so I am a little lost ... I have to put this if in another event or it is well here?

PS : i've ever tried something like that but it's gives me 0 all time.

Form1 testa = new Form1();
Point i = testa.Location;
Point z = testa.Location;
int res = i.X - z.X;
int pls = i.Y - z.Y;

Solution

  • Handle MouseDown and keep the point. Then in MouseClick event calculate the distance:

    Point p1;
    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        p1 = e.Location;
    }
    private void Form1_MouseClick(object sender, MouseEventArgs e)
    {
        MessageBox.Show($"dx = {e.Location.X - p1.X}, dy= {e.Location.Y - p1.Y}");
    }