【问题标题】:WPF event that triggers after the mouse stops moving鼠标停止移动后触发的 WPF 事件
【发布时间】:2012-11-04 07:29:38
【问题描述】:

我正在编写一个 WPF 应用程序。 我想在鼠标停止移动时触发一个事件。

这就是我尝试的方式。我创建了一个倒计时到 5 秒的计时器。每次鼠标移动时,此计时器都会“重置”。 这个思路是,鼠标停止移动的那一刻,定时器停止重置,从5倒计时到0,然后调用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");
}

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你需要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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-09
        • 1970-01-01
        • 2016-07-29
        • 2013-09-30
        • 1970-01-01
        相关资源
        最近更新 更多