Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MouseMove event in PictureBox is fired continuously even if the mouse is not moved

Why does MouseMove event of a PictureBox seem to be fired continuously even if the mouse is not moved? I have tried the following codes to prove it (by simply creating a new form with a PictureBox and a Label on it).

private void pictureBox1_MouseMove ( object sender, MouseEventArgs e )
{
  label1.Text = DateTime.Now.ToLongTimeString ( ) + ": " + e.X + "," + e.Y;
}
like image 691
Setyo N Avatar asked Dec 12 '11 23:12

Setyo N


2 Answers

Certain methods involving windows forms cause some level of internal refresh of the form, which (by my estimation) cause the form to 'pick up' the mouse position and thus fire the MouseMove event. One such method is associating a toolTip with the form. As a result,

int moveCount = 0;
ToolTip toolTip = new ToolTip();
private void form1_MouseMove(object sender, MouseEventArgs e)
{
    Trace.WriteLine(moveCount);
    moveCount++;
    toolTip.SetToolTip(this, "Hello world");
}

will fire continuously even if the mouse is not moved, while

int moveCount = 0;
private void form1_MouseMove(object sender, MouseEventArgs e)
{
    Trace.WriteLine(moveCount);
    moveCount++;
}

will fire only when the mouse is actually moved.

Having a look inside your MouseMove event for something that touches the form in a 'deep' way might help to reveal the source of the looping behavior.

like image 108
NiloCK Avatar answered Oct 18 '22 23:10

NiloCK


"pictureBox1_MouseMove" is just a delegate function. So with your code we can only assume that it was attached to MouseMove, and only MouseMove, in the designer.

Double check all references for "pictureBox1_MouseMove", and also keep in mind that Windows fires MouseMove messages on mouse click even if you don't move the mouse.

Worst case scenario you could store the Point e.Location in a local member variable ("oldLocation") and verify that the mouse actually moved before processing your command:

private Point oldLocation = Point.Empty;

private void pictureBox1_MouseMove ( object sender, MouseEventArgs e )
{
    if (e.Location != oldLocation)
    {
        oldLocation = e.Location;

        label1.Text = DateTime.Now.ToLongTimeString ( ) + ": " + e.X + "," + e.Y;
    }
}
like image 4
Trevor Elliott Avatar answered Oct 18 '22 21:10

Trevor Elliott