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!
Why not use a RepeatButton?
http://msdn.microsoft.com/en-us/library/ms746649(v=vs.85).aspx
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;
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With