2011-09-27 98 views
1

我想禁用一個按鈕- 爲了防止雙擊:在平板電腦上你推一次,它點擊兩次,這是我知道的最簡單的破解 -短期,但我注意到/調試的時間間隔可能是在實踐中過長; 50毫秒vs> 2秒。爲什麼DispatcherTimer Tick事件沒有按時發生?

只有一行啓動計時器,一行停止。隨機的間隔是50毫秒或更大。沒有CPU消耗,我只需用鼠標點擊我的4核心桌面PC上的按鈕。

會是什麼原因?

DispatcherTimer timerTouchDelay = new DispatcherTimer(); 

    protected override void OnMouseDown(MouseButtonEventArgs e) 
    { 
     //Init 
     if (timerTouchDelay.Interval.Milliseconds == 0) 
     { 
      timerTouchDelay.Tick += new EventHandler(timerTouchDelay_Tick); 
      timerTouchDelay.Interval = new TimeSpan(0, 0, 0, 0, 50); //ms 

     } 


     if(timerTouchDelay.IsEnabled) 
      return; 

     timerTouchDelay.Start(); 

     HandleKeyDown(); 
     base.OnMouseDown(e); 
    } 

    private void timerTouchDelay_Tick(object sender, EventArgs e) 
    { 
     timerTouchDelay.Stop(); 
    } 
+0

你不能在OnMouseDown函數中禁用它,並在第一個timerTouchDelay_Tick上啓用它。 – CodingBarfield

回答

2

要理解爲什麼是這樣的話,我會極力推薦的以下文章:

Comparing the Timer Classes in the .NET Framework Class Library

僅供參考,DispatcherTimer非常相似System.Windows.Forms.Timer,爲此筆者指出「如果你'尋找節拍器,你來錯了地方。「這個計時器不是按照確切的時間間隔「打勾」。

+0

我想我需要在我的代碼中替換所有DispatcherTimers,在慢速PC中,應用程序的行爲不同。但它是50毫秒和〜1 ++秒之間的巨大差異... –

2

而不是運行一個計時器,爲什麼不記錄上次按下按鈕的時間。如果超過50毫秒,請繼續執行操作,否則退出。

DateTime lastMouseDown = DateTime.MinValue; 

protected override void OnMouseDown(MouseButtonEventArgs e) 
{ 
    if(DateTime.Now.Subtract(lastMouseDown).TotalMilliseconds < 50) 
     return; 
    lastMouseDown = DateTime.Now; 

    HandleKeyDown(); 
    base.OnMouseDown(e); 
} 
+0

感謝這個想法,它的工作原理非常穩固。 VB6像靜態變量會很好,現在... –

相關問題