WPF: mouse left click and hold

How to re-execute an action when the left mouse button is pressed and held in WPF?

The following event handler for the UIElement.PreviewMouseLeftButtonDown event does not complete the task:

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 fall into the while loop, and the handler is called when the left mouse button is released.

+8
wpf mouseevent
source share
3 answers
+17
source share

Launch BackroundWorker, which will exit when the mouse is released. Set the flag with the mouse event, and also periodically check in the BackgroundWorker DoWork function. Make sure you use lock {} to access the flag.

Edit: if you want to access something in the user interface 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; })); 
+1
source share

Run the thread until MouseLeftButtonUp is started.

0
source share

All Articles