Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Mouse left button click and hold down handling

Tags:

mouseevent

wpf

How do I repetitively perform an action when the mouse left button is pressed and held down in WPF?

The following event handler for the UIElement.PreviewMouseLeftButtonDown event does not get the job done:

private void BaseButtonRight_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
           // keep performing action while mouse left button is pressed.  
           // Checking e.ButtonState works only for one click

        }

Execution does not even get into the while loop and handler is called when the left mouse button is released!

like image 251
Klaus Nji Avatar asked Jun 22 '11 16:06

Klaus Nji


2 Answers

Why not use a RepeatButton?

http://msdn.microsoft.com/en-us/library/ms746649(v=vs.85).aspx

like image 136
Itai Bar-Haim Avatar answered Nov 02 '22 07:11

Itai Bar-Haim


Start a BackroundWorker which exits when the mouse has been released. Set a flag with the mouse up event and also check periodically in the BackgroundWorker DoWork function. Make sure you use lock { } around accessing the flag.

Edit: in case you want to access something on the UI thread, use Dispatcher.BeginInvoke, for example:

Dispatcher.BeginInvoke(new ThreadStart(delegate
{
    ComboBoxItem selItem = ComboboxConnectString.SelectedItem as ComboBoxItem;
    if (selItem != null && selItem.Tag is string)
        ComboboxConnectString.Text = (string)selItem.Tag;
}));
like image 1
Ed Bayiates Avatar answered Nov 02 '22 07:11

Ed Bayiates