Use a global mouse hook
Use a global mouse hook to monitor and optionally block mouse events.
An example implementation of global mouse/keyboard hook is MouseKeyHook nuget package and the GitHub source code globalmousekeyhook.
Blocking only user clicks
If you want to prevent the user from clicking but keep sending automation clicks, you can raise a flag to signal to the mouse down event not to block the next click.
Note: There is a small chance that in the small amount of time from when the flag was raised until the event filters the next mouse down, a user click will be captured by the hook instead of the automation click.
Blocking mouse down events example
In the following code, I give an example of using MouseKeyHook nuget package to prevent mouse clicks globally for a TimeSpan amount of time:
Required using declarations:
using System.Diagnostics;
using Gma.System.MouseKeyHook;
Code:
// Global hook
private IKeyboardMouseEvents _globalHook;
// Stopwatch to count the amount of time the global mouse down events are blocked
private Stopwatch _stopwatch = new Stopwatch();
// The amount of time to block global mouse down events
private TimeSpan _timeSpan;
// Attach global hook
private void Subscribe()
{
_globalHook = Hook.GlobalEvents();
_globalHook.MouseDownExt += GlobalHookMouseDownExt;
}
// Remove global hook
private void Unsubscribe()
{
_globalHook.MouseDownExt -= GlobalHookMouseDownExt;
_globalHook.Dispose();
}
// Global hook mouse down event
private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
{
if(_stopwatch.IsRunning)
{
if(_stopwatch.Elapsed < _timeSpan)
{
e.Handled = true;
}
else
{
_stopwatch.Stop();
}
}
}
// Block global mouse down events for timeSpan amount of time
private void BlockMouseDown(TimeSpan timeSpan)
{
_timeSpan = timeSpan;
_stopwatch.Restart();
}
Usage:
// Attach global hook
Subscribe();
...
// Block mouse down event for 10 seconds
BlockMouseDown(TimeSpan.FromSeconds(10));