How to stop a user from clicking anywhere on the screen during session activity

Viewed 277

I am writing an automation application where a program is opened and while that program is opened I don't want the user to be allowed to click anywhere on the screen as that will cause the automation to possibly fail at specific points.I have not been able to find anyone who has a solution to this, most of the solutions only provide answers for buttons or specific windows, but I want to disable the mouse click entirely for the user. Is there a way to do this?

1 Answers

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));

Related