VBA to stop computer auto-locking

kevnaff

Member
Local time
Today, 00:40
Joined
Mar 25, 2021
Messages
174
Hi all.

I have found the following code which should help to stop my computer automatically locking, by moving the cursor using the Form's Timer.

I am unsure where I should place the code up until the End Type. I'm not familar with how modules work, so I don't know whether it's meant to go in a module.

Could anybody help with this please?

Code:
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Private Declare PtrSafe Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long

Private Type POINTAPI
    x As Long
    y As Long
End Type

Private Sub Form_Timer()
    Dim p As POINTAPI
    ' Get the current mouse position
    GetCursorPos p
    ' Move the mouse cursor slightly to the right
    SetCursorPos p.x + 1, p.y
    ' Wait a brief moment
    Sleep 50
    ' Move the mouse cursor back to the original position
    SetCursorPos p.x, p.y
End Sub
 
You must place the code up until the End Type at the top of the same form module where you place the Private Sub Form Timer()...End sub.
Example attached
 

Attachments

Try moving the mouse more. Because MoveMove events commonly occur like a fire-hose, lots of software discards mouse move events where the distance of travel is below a certain threshold. I don't know this is the case here, but if you are not getting other errors, and your code is simply not working, try bigger moves.
 
If you have a screen saver, you can write code that detects when the screensaver.exe process becomes active and then move your mouse only at that time. I think you have about a 2-3 second grace period, if your pc is anything like mine
 

Users who are viewing this thread

Back
Top Bottom