我正在写一个WPF应用程序.我想在鼠标停止移动时触发事件.
这就是我尝试这样做的方式.我创建了一个计时器,倒计时为5秒.每次鼠标移动时,此计时器都会"重置".这个想法是鼠标停止移动的那一刻,计时器停止重置,并从5倒数到零,然后调用tick事件处理程序,它显示一个消息框.
好吧,它没有按预期工作,它充满了警报信息.我究竟做错了什么?
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");
}
Run Code Online (Sandbox Code Playgroud)
没有必要在每个MouseMove事件上创建一个新的计时器.只需停止并重新启动即可.并确保它在Tick处理程序中停止,因为它应该只被触发一次.
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();
}
Run Code Online (Sandbox Code Playgroud)
你需要unhook在event之前再次挂钩 - 就像这样 -
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();
}
Run Code Online (Sandbox Code Playgroud)
说明
你所做的就是当鼠标移动时,你创建一个新的DispatcherTimer实例并在没有它的情况下挂钩Tick事件unhooking the event for previous instance.因此,一旦计时器停止所有实例,您就会看到泛洪消息.
此外,你应该取消它,否则以前的实例将不会,garbage collected因为它们仍然是strongly referenced.