I am writing a WPF application. I want to trigger an event once the mouse stops moving.
This is how I tried to do it. I created a timer which counts down to 5 seconds. This timer is "reset" every time the mouse moves. This idea is that the moment the mouse stops moving, the timer stops being reset, and counts down from 5 to zero, and then calls the tick event handler, which displays a message box.
Well, it doesn't work as expected, and it floods me with alert messages. What am I doing wrong?
DispatcherTimer timer;
private void Window_MouseMove(object sender, MouseEventArgs e)
{
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 5);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Mouse stopped moving");
}
It is not necessary to create a new timer on every MouseMove event. Just stop and restart it. And also make sure that it is stopped in the Tick handler, since it should be fired only once.
private DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Tick += timer_Tick;
}
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
MessageBox.Show("Mouse stopped moving");
}
private void Window_MouseMove(object sender, MouseEventArgs e)
{
timer.Stop();
timer.Start();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With