假設我有一個按鈕,我想要以下行爲:幾秒鐘後如何獲取MouseDown?
當我點擊按鈕時,它激發了一個事件 - 好的,這很容易。
現在,如果我點擊並等待,幾秒鐘後它會啓動另一個事件。例如彈出菜單...
該怎麼辦?
假設我有一個按鈕,我想要以下行爲:幾秒鐘後如何獲取MouseDown?
當我點擊按鈕時,它激發了一個事件 - 好的,這很容易。
現在,如果我點擊並等待,幾秒鐘後它會啓動另一個事件。例如彈出菜單...
該怎麼辦?
DispatcherTimer PopupTimer = new DispatcherTimer();
PopupTimer.Tick += new EventHandler(PopupTimerTick);
PopupTimer.Interval = new TimeSpan(0, 0, 0, 0,5);
private void PopupTimerTick(object sender, EventArgs e)
{
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
// If still pressed showing popup
((Storyboard)Resources["ShowPopup"]).Begin();
PopupTimer.Stop();
}
}
private void ImageOnMouseDown(object sender, MouseButtonEventArgs e)
{
PopupTimer.Start();
e.Handled = true;
}
private void ImageOnMouseUp(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
if (Popup.IsOpen == false)
{
((Storyboard)Resources["ShowPopup"]).Stop();
// Here the operation that works on the click
}
}
你在檢查MouseUp事件嗎?
如果用戶按住鼠標按鈕2秒鐘以顯示彈出式菜單,您說的是什麼?
我會做的是在MouseDown事件上創建一個單獨的線程,等待2秒鐘。如果MouseUp事件在到期前觸發,則不執行任何操作,否則請執行事件。
// This event will be used for tracking if the MouseUp has been received
private System.Threading.AutoResetEvent _stopTrigger;
private void OnMouseDown(object sender, MouseButtonEventArgs e)
{
if (this._stopTrigger == null)
{
this._stopTrigger = new System.Threading.AutoResetEvent(false);
}
Action popupProcess = new Action(this.ShowPopupAfterTime);
// Make the Popup process on a separate thread
popupProcess.BeginInvoke(null, null);
}
private void OnMouseUp(object sender, MouseButtonEventArgs e)
{
if (this._stopTrigger != null)
{
// Sends the signal to the ShowPopupAfterTime that it should NOT display the pop up
// IIt will make WaitOne return true and not go into the if statement
this._stopTrigger.Set();
}
}
private void ShowPopupAfterTime()
{
// Will enter the if after 2 seconds
if (!this._stopTrigger.WaitOne(2000))
{
// This means it has NOT be trigged thus I can display the popup
// DISPLAY POPUP
// DON"T FORGET you are on a different thread here, NOT UI thread. You will have to use the Dispatcher to get back
// to the UI thread to display the popup
}
}
很好的解決方法,謝謝 – 2010-07-31 07:42:43
查一查定時器()和DispatcherTimer()
我會使用線程這樣
private void mousedownEvent(object sender, MouseButtonEventArgs e)
{
//Fire off a thread which will do the waiting in the background
new Thread(delegate()
{
//Wait for 2 seconds
Thread.Sleep(2000);
//dump a dowork() method onto the main thread
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
{
doWork(sender);
}));
return;
}).Start();
}
private void doWork(object sender)
{
//if the button is still pressed
if ((sender as UIElement).IsMouseOver && Mouse.LeftButton == MouseButtonState.Pressed)
{
//continue here
}
}
它會檢查按下鼠標鍵,然後在2秒後再次檢查,而不會停止主要的應用程序線程。我wou't檢查按鈕被按下的整個時間所以這可能是也可能不是你
重要巴蒂爾
您可以在MouseDown事件和計時器滴答事件運行2秒定時檢查的內容需要。你可以停止你的計時器。
「click and wait」是什麼意思?你的意思是你按住鼠標按鈕,還是喲意味着你點擊一個按鈕,它做了什麼,然後在幾秒鐘後發生了其他事情?那麼「彈出菜單」是什麼意思?上下文菜單? – 2010-07-30 15:26:55