How to remove all the associated in built events of a control in WPF?
There is no easy way to remove all events queued on the Dispatcher
. Even if there were, you wouldn't want to do so because it would break many WPF controls that rely on background events to update their data structures and UI.
However, there is an easy way to discard selected input events from the queue, such as keyboard, mouse and stylus events:
Create a "FlushInputQueue" method that registers an event handler with
InputManager.PreprocessInput
, invokes aDispatcherOperation
at Input priority, then removes the event handler.When the
PreprocessInput
event fires, check the input message and set theHandled
flag to true if you want to discard it.
Here is some code to get you started:
public void FlushInputQueue()
{
PreProcessInputEvent handler = (obj, e) =>
{
if(ShouldFlushEvent(e.StagingItem.Input))
e.StagingItem.Input.Handled = true;
};
InputManager.PreProcessInput += handler;
Dispatcher.Invoke(DispatcherPriority.Input, new Action(() => {}));
InputManager.PreProcessInput -= handler;
}
private bool ShouldFlushEvent(InputEventArgs e)
{
// Example only:
return e is MouseEventArgs || e is KeyboardEventArgs || e is StylusEventArgs;
}
The ShouldFlushEvent method should probably be customized for your particular scenario to avoid throwing out events that should be kept.
One last thought: Have you considered doing your long-running operation on a background thread so the UI remains responsive? Many times this is a better solution than locking the UI when an item is clicked on, and removes any reason for wanting to flush the queue.