在 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.Tick += dispatcherTimer_Tick; // try without that new EventHandler(...)

将附上第二个处理。因此,在第一秒之后,sec 将为 2,因为该事件被调用了两次。

您可以尝试处理 PreviewMouseUp 上的 dispatcherTimer 变量并将其设置为 null 并在 PreviewMouseDown 上创建一个新实例。

或者另一种选择是,在 PreviewMouseUp 上,您可以

dispatcherTimer.Tick -= dispatcherTimer_Tick;
sec = 0;

-= 将分离事件处理程序。

您不需要 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;
    }
}