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



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

没有必要在每个 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();
}

你需要unhookevent,然后再像这样钩住它 -

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

解释

您所做的是,每当鼠标移动时,您都会创建一个 DispatcherTimer 的新实例,并将 Tick 事件挂接到它而不unhooking the event for previous instance。因此,一旦所有实例的计时器停止,您就会看到泛洪消息。

此外,您应该取消挂钩它,否则以前的实例将不会garbage collected,因为它们仍然strongly referenced

最新更新