簡體   English   中英

鼠標停止移動后觸發的WPF事件

[英]WPF event that triggers after the mouse stops moving

我正在寫一個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();
}

你需要在再次掛鈎之前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();
}

說明

你所做的是每當鼠標移動時,你創建一個新的DispatcherTimer實例並將Tick事件掛鈎到它而不unhooking the event for previous instance 因此,一旦計時器停止所有實例,您就會看到泛洪消息。

此外,您應該取消它,否則以前的實例將不會被garbage collected因為它們仍然被strongly referenced

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM