C# 鼠标停止移动后触发的WPF事件

C# 鼠标停止移动后触发的WPF事件,c#,.net,wpf,C#,.net,Wpf,我正在写一个WPF应用程序。 我想在鼠标停止移动后触发一个事件 我就是这样做的。我创建了一个倒计时到5秒的计时器。每次鼠标移动时,此计时器都会“重置”。 这个想法是,当鼠标停止移动时,计时器停止重置,从5倒计时到零,然后调用tick事件处理程序,该处理程序显示一个消息框 嗯,它没有像预期的那样工作,它给我大量的警告信息。我做错了什么 DispatcherTimer timer; private void Window_MouseMove(object sender, MouseEventArg

我正在写一个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");
}

在像这样再次钩住
事件之前,需要
取消钩住
事件-

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();
}
解释

您要做的是,每当鼠标移动时,都会创建Dispatchermer的新实例,并将勾号事件挂到该实例上,而不必
为以前的实例取消勾号。因此,一旦所有实例的计时器停止,您就会看到泛洪消息


另外,您应该将其取消挂钩,否则前一个实例将不会被垃圾收集
,因为它们仍然是
强引用的

无需在每个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();
}