Have you ever wanted to lockout your user’s input temporarily while you perform some operation? Well, VBA offers you that possibility and that’s what we’re going to explore in this article.
The BlockInput API offers us a simple and convenient way of temporarily disabling user interaction with the system..
BlockInput Basics
We must first include the necessary API declaration(s):
#If VBA7 Then
Private Declare PtrSafe Function BlockInput Lib "user32" (ByVal fBlock As Long) As Long
#Else
Private Declare Function BlockInput Lib "user32" (ByVal fBlock As Long) As Long
#End If
and then we can lock/block inputs by simply doing:
BlockInput True
That said, the function actually returns a value of 0 if it fails, so it is better practice to actually use it by doing:
Dim Ret As Long Ret = BlockInput(True) if Ret <> 0 Then 'it worked Else 'We have a problem End If
The Limitations
Sadly, there is a colossal limitation with the usage of this API and it’s not even mentioned in the documentation!
The API must be called by a process that is ‘Run as administrator’ otherwise is fails. We can use GetLastError() to gather information on failures, which in the specific case of the API being run normally (not ‘Run as administrator’, so without elevated proviledges) returns an “Error 5: Access is denied.”.
Also, from the help documentation on the API:
- The thread that blocked input unexpectedly exits without calling BlockInput with fBlock set to FALSE. In this case, the system cleans up properly and re-enables input.
- The user presses CTRL+ALT+DEL or the system invokes the Hard System Error modal message box (for example, when a program faults or a device fails).
So at the end of the day, the BlockInput API can be useful, but only under the right conditions.
