Abdulsalam Elsharif
Abdulsalam Elsharif

Reputation: 5101

Hold down mouse event in WPF

I'm trying to hold down mouse event using PreviewMouseDown and DispatcherTimer as following:

 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;
        }
    }

This code works, BUT the first mouse down takes 3 seconds to display the message, after that the time to show the message is decreased (less that 3 seconds)

Upvotes: 0

Views: 2241

Answers (2)

mm8
mm8

Reputation: 169150

You don't need a DispatcherTimer to do this. You could handle the PreviewMouseDown and the PreviewMouseUp events.

Please refer to the following sample code.

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;
    }
}

Upvotes: 2

Andrei Neagu
Andrei Neagu

Reputation: 896

The second time this gets called

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

a second handled will be attached. So, after the first second, sec will be 2, since the event is called twice.

You can try to dispose and set to null the dispatcherTimer variable on the PreviewMouseUp & create a new instance on the PreviewMouseDown.

Or another option would be, on the PreviewMouseUp, you can

dispatcherTimer.Tick -= dispatcherTimer_Tick;
sec = 0;

-= will detach the event handler.

Upvotes: 1

Related Questions