WPF事件触发鼠标停止移动后, [英] WPF event that triggers after the mouse stops moving
问题描述
我写一个WPF应用程序。 我想触发一个事件一旦鼠标停止移动。
这是我如何试图做到这一点。我创建了一个定时器,倒计时5秒。此计时器重置,每次鼠标移动。 这种想法是,当下的鼠标停止移动,定时器停止被重置,并倒数5到零,然后调用Tick事件处理程序,它会显示一个消息框。
那么,它并不会达到预期效果,而且洪水给我警报消息。我究竟做错了什么?
DispatcherTimer定时器;
私人无效Window_MouseMove(对象发件人,发送MouseEventArgs E)
{
定时器=新DispatcherTimer();
timer.Interval =新时间跨度(0,0,5);
timer.Tick + =新的EventHandler(timer_Tick);
timer.Start();
}
无效timer_Tick(对象发件人,EventArgs的)
{
的MessageBox.show(鼠标停止移动);
}
您需要解开
的事件
前再次钩住这样的 -
私人无效poc_MouseMove(对象发件人,发送MouseEventArgs E)
{
如果(定时器!= NULL)
{
timer.Tick- = timer_Tick;
}
定时器=新DispatcherTimer();
timer.Interval =新时间跨度(0,0,5);
timer.Tick + =新的EventHandler(timer_Tick);
timer.Start();
}
说明
每当鼠标移动时,将创建DispatcherTimer的新实例,并挂钩Tick事件而不用担心会有脱钩的事件previous实例
什么,你做的是。因此,你看到洪水淹没的消息后,计时器停止所有实例。
此外,你应该解开它,否则previous实例不会被垃圾回收
,因为他们仍然坚决引用
。
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");
}
You need to unhook
the event
before hooking it again like this -
private void poc_MouseMove(object sender, MouseEventArgs e)
{
if (timer != null)
{
timer.Tick-= timer_Tick;
}
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 5);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
Explanation
What you doing is whenever a mouse moves, you create a new instance of DispatcherTimer and hook Tick event to it without unhooking the event for previous instance
. Hence, you see flooded messages once timer stops for all the instances.
Also, you should unhook it otherwise previous instance won't be garbage collected
since they are still strongly referenced
.
这篇关于WPF事件触发鼠标停止移动后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!