簡體   English   中英

在WPF中按住鼠標事件

[英]Hold down mouse event in WPF

我正在嘗試使用PreviewMouseDownDispatcherTimer按住鼠標事件,如下所示:

 private void button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
        dispatcherTimer.Start();
    }

 private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        _sec = _sec + 1;
        if (_sec == 3)
        {
            dispatcherTimer.Stop();
            MessageBox.Show(_sec.ToString());
            _sec = 0;
            return;
        }
    }

此代碼有效,但是第一次按下鼠標需要3秒鍾來顯示消息,此后減少了顯示消息的時間(少於3秒)

您不需要DispatcherTimer來執行此操作。 您可以處理PreviewMouseDown和PreviewMouseUp事件。

請參考以下示例代碼。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        PreviewMouseDown += Window3_PreviewMouseDown;
        PreviewMouseUp += Window3_PreviewMouseUp;
    }

    DateTime mouseDown;
    private void Window3_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        mouseDown = DateTime.Now;
    }

    readonly TimeSpan interval = TimeSpan.FromSeconds(3);
    private void Window3_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        if (DateTime.Now.Subtract(mouseDown) > interval)
            MessageBox.Show("Mouse was held down for > 3 seconds!");
        mouseDown = DateTime.Now;
    }
}

第二次被調用

dispatcherTimer.Tick += dispatcherTimer_Tick; // try without that new EventHandler(...)

第二個處理將被附加。 因此,在第一秒之后,秒將為2,因為該事件被調用了兩次。

您可以嘗試在PreviewMouseUp上處置並將DispatcherTimer變量設置為空,並在PreviewMouseDown上創建一個新實例。

或者另一個選擇是,在PreviewMouseUp上,您可以

dispatcherTimer.Tick -= dispatcherTimer_Tick;
sec = 0;

-=將分離事件處理程序。

暫無
暫無

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

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