Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple MouseHover events in a Control

Tags:

c#

winforms

I'm trying to implement a custom control in C# and I need to get events when the mouse is hovered. I know there is the MouseHover event but it only fires once. To get it to fire again I need to take the mouse of the control and enter it again.

Is there any way I can accomplish this?

like image 435
João Matos Avatar asked May 01 '09 02:05

João Matos


1 Answers

Let's define "stops moving" as "remains within an x pixel radius for n ms".

Subscribe to the MouseMove event and use a timer (set to n ms) to set your timeout. Each time the mouse moves, check against the tolerance. If it's outside your tolerance, reset the timer and record a new origin.

Pseudocode:

Point lastPoint;
const float tolerance = 5.0;

//you might want to replace this with event subscribe/unsubscribe instead
bool listening = false;

void OnMouseOver()
{
    lastpoint = Mouse.Location;
    timer.Start();
    listening = true; //listen to MouseMove events
}

void OnMouseLeave()
{
    timer.Stop();
    listening = false; //stop listening
}

void OnMouseMove()
{
    if(listening)
    {
        if(Math.abs(Mouse.Location - lastPoint) > tolerance)
        {
            //mouse moved beyond tolerance - reset timer
            timer.Reset();
            lastPoint = Mouse.Location;
        }
    }
}

void timer_Tick(object sender, EventArgs e)
{
    //mouse "stopped moving"
}
like image 172
lc. Avatar answered Oct 05 '22 22:10

lc.