Skip to content

Instantly share code, notes, and snippets.

@MatthewSteeples
Created February 26, 2015 19:09
Show Gist options
  • Save MatthewSteeples/ce7114b4d3488fc49b6a to your computer and use it in GitHub Desktop.
Save MatthewSteeples/ce7114b4d3488fc49b6a to your computer and use it in GitHub Desktop.
Powershell Script to keep the mouse moving
Add-Type -AssemblyName System.Windows.Forms
while ($true)
{
$Pos = [System.Windows.Forms.Cursor]::Position
$x = ($pos.X % 500) + 1
$y = ($pos.Y % 500) + 1
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)
Start-Sleep -Seconds 10
}
@AnonQuebec
Copy link

AnonQuebec commented Apr 23, 2021

Found something good, maybe can be added.

Sources: InunoTaishou

https://www.autoitscript.com/forum/topic/187597-detect-keyboardmouse-activity-and-inactivity-within-script/

#include <GUIConstants.au3>
#include <WindowsConstants.au3>
#include <WinAPI.au3>

Global $hMain = GUICreate("Test", 400, 400)
Global $iActiveTimer = TimerInit()

GUIRegisterMsg($WM_MOUSEMOVE, WM_MOUSEMOVE)
GUIRegisterMsg($WM_KEYDOWN, Active)
GUIRegisterMsg($WM_KEYUP, Active)
GUIRegisterMsg($WM_LBUTTONDOWN, Active)
GUIRegisterMsg($WM_LBUTTONUP, Active)
GUIRegisterMsg($WM_RBUTTONDOWN, Active)
GUIRegisterMsg($WM_RBUTTONUP, Active)
GUIRegisterMsg($WM_MBUTTONDOWN, Active)
GUIRegisterMsg($WM_MBUTTONUP, Active)

GUISetState(@SW_SHOW, $hMain)

While (True)
Switch (GUIGetMsg())
Case $GUI_EVENT_CLOSE
Exit 0
Case Else
ToolTip("Inactive for " & Round(TimerDiff($iActiveTimer) / 1000, 0) & "s")
If (Round(TimerDiff($iActiveTimer) / 1000, 0) >= 5) Then FunctionA()
EndSwitch
WEnd

Func FunctionA()
While (Round(TimerDiff($iActiveTimer) / 1000, 0) >= 5)
ToolTip("FunctionA()")
Sleep(100)
WEnd
ToolTip("")
EndFunc

Func Active($hWnd, $iMsg, $wParam, $lParam)
$iActiveTimer = TimerInit()
EndFunc

Func WM_MOUSEMOVE($hWnd, $iMsg, $wParam, $lParam)
Local Static $aLastPos[2]
Local $iX = _WinAPI_LoWord($lParam)
Local $iY = _WinAPI_HiWord($lParam)

If ($iX <> $aLastPos[0] or $iY <> $aLastPos[1]) Then
    $iActiveTimer = TimerInit()
    $aLastPos[0] = $iX
    $aLastPos[1] = $iY
EndIf

EndFunc

Sorry for the formatting I'm new in commenting

@nasibjabiyev
Copy link

Thanks bro Its working well

@ashokexotic
Copy link

How should I run this script? Can someone give me a step by step process please ?

@nasibjabiyev
Copy link

nasibjabiyev commented Apr 29, 2021 via email

@mtxadmin
Copy link

mtxadmin commented May 7, 2021

Incredible, just incredible! I was sure that Powershell cannot move mouse cursor. We used AutoIT for it.

Wow! It's a real breakthrough for me.

Update: up here is AutoIt script too :-)

@crotodebsas
Copy link

Awesome and we'll explained @stvhwrd ! Just what I need.

How can I add a restriction to DO NOTHING for example, between 12,30pm and 1,30pm and after 7pm?

Thanks

@iq220
Copy link

iq220 commented Sep 24, 2021

Simple and does what it states! Thanks

@outtersg
Copy link

Thank you @MatthewSteeples and @AndrewDavis (… for sharing it, but for not overengineering it too)!

It helped here to make a fix run all night long, through a Citrix VPN that normally closes connection when detecting no activity (one-shot database cleaning for a rotten three-year history with duplicates on thousands of clients).

@Dport406x
Copy link

Dport406x commented Dec 8, 2021

I do not understand script language and I have read through this whole thread and I think this or a modified version of this is what I am looking for.

I need an active window that is in full screen to have mouse motion on it every five minutes to keep it 'alive'. Is that what this does and if not, how do I modify it to do that? The computer does not have sleep or hibernate activated.

@Dport406x
Copy link

So, I tried to run it. I got several errors.

At C:\Users\user\Desktop\Stay_alive.ps1:6 char:34

  • Global $iActiveTimer = TimerInit()
  •                              ~
    

An expression was expected after '('.
At C:\Users\user\Desktop\Stay_alive.ps1:8 char:30

  • GUIRegisterMsg($WM_MOUSEMOVE, WM_MOUSEMOVE)
  •                          ~
    

Missing expression after ','.
At C:\Users\user\Desktop\Stay_alive.ps1:8 char:31

  • GUIRegisterMsg($WM_MOUSEMOVE, WM_MOUSEMOVE)
  •                           ~~~~~~~~~~~~
    

Unexpected token 'WM_MOUSEMOVE' in expression or statement.
At C:\Users\user\Desktop\Stay_alive.ps1:8 char:30

  • GUIRegisterMsg($WM_MOUSEMOVE, WM_MOUSEMOVE)
  •                          ~
    

Missing closing ')' in expression.
At C:\Users\user\Desktop\Stay_alive.ps1:8 char:43

  • GUIRegisterMsg($WM_MOUSEMOVE, WM_MOUSEMOVE)
  •                                       ~
    

Unexpected token ')' in expression or statement.
At C:\Users\user\Desktop\Stay_alive.ps1:9 char:28

  • GUIRegisterMsg($WM_KEYDOWN, Active)
  •                        ~
    

Missing expression after ','.
At C:\Users\user\Desktop\Stay_alive.ps1:9 char:29

  • GUIRegisterMsg($WM_KEYDOWN, Active)
  •                         ~~~~~~
    

Unexpected token 'Active' in expression or statement.
At C:\Users\user\Desktop\Stay_alive.ps1:9 char:28

  • GUIRegisterMsg($WM_KEYDOWN, Active)
  •                        ~
    

Missing closing ')' in expression.
At C:\Users\user\Desktop\Stay_alive.ps1:9 char:35

  • GUIRegisterMsg($WM_KEYDOWN, Active)
  •                               ~
    

Unexpected token ')' in expression or statement.
At C:\Users\user\Desktop\Stay_alive.ps1:10 char:26

  • GUIRegisterMsg($WM_KEYUP, Active)
  •                      ~
    

Missing expression after ','.
Not all parse errors were reported. Correct the reported errors and try again.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : ExpectedExpression

What next?

@Dport406x
Copy link

Dport406x commented Dec 9, 2021

The link in your post leads to a 404 error, and I don't see any {}...

@MatthewSteeples
Copy link
Author

MatthewSteeples commented Dec 9, 2021

@Dport406x Andrew is talking about this post: https://gist.github.com/MatthewSteeples/ce7114b4d3488fc49b6a#gistcomment-2946126

( @AndrewDavis: There's a link in a later post that does return a 404 for some reason)

@cmeza
Copy link

cmeza commented Jan 3, 2022

Pro Tip: if you don't know what the script is doing or even how to load it, probably a good idea to NOT run it.

If you can, try something simpler, running Windows Media Player the app kept my laptop alive. I didn't even have to play anything. I was running an 1sec MP3 of silence on repeat, but 1 day I forgot to push play & went downstairs for lunch & my laptop was still unlocked.

@jasonpeterson0984
Copy link

So it works great on my home laptop. Any tricks for me to get it on my work laptop( which is where I need it)
Like if i pur the script into my rubber ducky just how it is, will it run?
I don't have access to github on work laptop... I tried.

@kmarf
Copy link

kmarf commented May 4, 2022

Clear-Host
Echo "Keep-alive with Scroll Lock..."

$WShell = New-Object -com "Wscript.Shell"

while ($true)
{
  $WShell.sendkeys("{SCROLLLOCK}")
  Start-Sleep -Milliseconds 100
  $WShell.sendkeys("{SCROLLLOCK}")
  Start-Sleep -Seconds 240
}

I can confirm that this works great for me, many thanks for sharing AndrewDavis :)

@jimb2g
Copy link

jimb2g commented Jul 1, 2022

I have a little dot writer section in the loop

  # dot 
  write-host '.' -NoNewline;
  $Count++
  # newline ?
  if ( -not ( $count % $dotsperline ) ){
    write-host
  }

And I exit on a keypress

  # exit on keypress
  if ( [Console]::KeyAvailable ) {
    $keypress = [Console]::ReadKey($true)
    $sw.stop()  # stop stopwatch
    Write-Host
    Write-Host "Elapsed $([int]$sw.Elapsed.TotalSeconds) seconds"
    break
  }

@horsebuzz
Copy link

I have a little dot writer section in the loop

  # dot 
  write-host '.' -NoNewline;
  $Count++
  # newline ?
  if ( -not ( $count % $dotsperline ) ){
    write-host
  }

And I exit on a keypress

  # exit on keypress
  if ( [Console]::KeyAvailable ) {
    $keypress = [Console]::ReadKey($true)
    $sw.stop()  # stop stopwatch
    Write-Host
    Write-Host "Elapsed $([int]$sw.Elapsed.TotalSeconds) seconds"
    break
  }

Can you please post full script here?

@jimb2g
Copy link

jimb2g commented Jul 20, 2022

# Simulate user activity to keep session active
$sleep  = 2    # sleep time, seconds
$line   = 60   # dots/line
# uses techniques from https://gist.github.com/MatthewSteeples/ce7114b4d3488fc49b6a

$sw = [System.Diagnostics.Stopwatch]::StartNew()
$ws = New-Object -com "Wscript.Shell"

while ( $true ) {

  # # move mouse - DOESN'T WORK
  # $Pos = [System.Windows.Forms.Cursor]::Position
  # $x = ($pos.X % 500) + 2
  # $y = ($pos.Y % 500) + 2
  # [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)
  
  # toggle scroll lock
  $WShell.sendkeys( "{SCROLLLOCK}" )
  Start-Sleep -Milliseconds 100
  $WShell.sendkeys( "{SCROLLLOCK}" )
  Start-Sleep -Seconds $sleep
  
  # dot 
  write-host '.' -NoNewline
  $Count++
  # newline ?
  if ( -not ( $count % $line ) ) {
    write-host
  } 
  
  Start-Sleep $sleep
  
  # exit on keypress
  if ( [Console]::KeyAvailable ) { 
    $keypress = [Console]::ReadKey($true)  # clear the key press
    Write-Host
    $sw.stop()
    Write-Host "Elapsed $([int]$sw.Elapsed.TotalSeconds) seconds"
    break
  }
}

[not extensively tested]

@makc
Copy link

makc commented Nov 15, 2022

I ran mouse move script directly on power shell window, and now mouse keeps on moving. I want help in reverting it.

@cody606 just run 2nd copy with + changed to -, it will revert what 1st one did

@makc
Copy link

makc commented Nov 15, 2022

I ran mouse move script directly on power shell window, and now mouse keeps on moving. I want help in reverting it.

@cody606 just run 2nd copy with + changed to -, it will revert what 1st one did

That's the most retarded thing I've read all week.

I guess you dont read much then? Maybe give it try, you might like it

@roeniss
Copy link

roeniss commented Nov 21, 2022

I knew it. I was not the only one!

@quonic
Copy link

quonic commented Jan 9, 2023

My version of the same thing, but only needs to rely on detecting if CapsLock is toggled on to quit. Uses the GetKeyState function from user32.dll and [System.Windows.Forms.SendKeys]::SendWait() to toggle ScrollLock. No need to rely on WsScript. Pure Win32 API and .Net!

This was derived from a script I wrote that pressed the space bar over and over when ScrollLock was on, but quit when CapsLock was toggled on.

$TimeToQuit = $false
$Signature = @'
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)] 
    public static extern short GetKeyState(int keyCode);
'@
Add-Type -AssemblyName System.Windows.Forms
Add-Type -MemberDefinition $Signature -Name Keyboard -Namespace WeakShell

Write-Output "Starting Show As Active!"
Write-Output "Turn on Caps Lock to quit."

do {
    # "(([int][WeakShell.Keyboard]::GetKeyState(0x14)) -band 0xffff) -eq 0" = True when CapsLock is off
    if ((([int][WeakShell.Keyboard]::GetKeyState(0x14)) -band 0xffff) -eq 0) {
        [System.Windows.Forms.SendKeys]::SendWait("{ScrollLock}")
        Start-Sleep -Seconds 1
    }
    else {
        $TimeToQuit = $true
        Write-Output "Caps Lock on, quiting"
    }
}while ($TimeToQuit -eq $false)

@danielhall95
Copy link

danielhall95 commented Feb 28, 2023

I like the heartbeat version with the indicator light. Used some of the above code and also preferred the CAPSLOCK light to remind me that it's running in the background as my laptop doesn't have a full-size keyboard. Lastly, added the ability to quit based on GetKeyState using quonic's code above, with a reset state in the beginning so you don't have to toggle PrtSc manually.

#
# -- NoSleep --
# Keep your computer awake by programmatically pressing the CAPSLOCK key every X seconds
#
param($sleep = 3) # seconds
$announcementInterval = 10 # loops



Clear-Host
$key = 0x2C
$printScreenState = [int][WeakShell.Keyboard]::GetKeyState($key) -band 0xffff
Write-Output "PrintScreen Key State: $printScreenState"
Write-Output ""
#Start-Sleep -Milliseconds 100

if ($printScreenState -eq 1){
    Write-Output "Resetting PrintScreenState.."
    Start-Sleep -Milliseconds 200
    [System.Windows.Forms.SendKeys]::SendWait("{PRTSC}") #toggle PrintScreen On
    Start-Sleep -Milliseconds 500
    [System.Windows.Forms.SendKeys]::SendWait("{ESC}")
     #toggle PrintScreen On
    [System.Windows.Forms.SendKeys]::SendWait("{ESC}") #toggle PrintScreen Off
    Write-Output "PrintScreenState Reset..";Write-Output ""; $printScreenState = [int][WeakShell.Keyboard]::GetKeyState($key) -band 0xffff
    Write-Output "PrintScreen Key State: $printScreenState";Write-Output ""
}

Write-Output "Starting Show As Active!"
Write-Host "Executing Print Screen-toggle NoSleep routine. Runs every $sleep seconds..."
Write-Host "Start time:" $(Get-Date -Format "dddd MM/dd HH:mm (K)")
Write-Output "Press Print Screen to quit."

$WShell = New-Object -com "Wscript.Shell"
$date = Get-Date -Format "dddd MM/dd HH:mm (K)"
$TimeToQuit = $false
$Signature = @'
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)] 
    public static extern short GetKeyState(int keyCode);
'@
Add-Type -AssemblyName System.Windows.Forms
#Add-Type -MemberDefinition $Signature -Name Keyboard -Namespace WeakShell



# Some environments don't support invocation of this method.
try {
    $stopwatch = [system.diagnostics.stopwatch]::StartNew()
} catch {
   Write-Host "Couldn't start the stopwatch."
}



#Write-Host "<3" -fore red

$index = 0
do{
    
    $printScreenState = [int][WeakShell.Keyboard]::GetKeyState($key) -band 0xffff
    
    #for Key State: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes 
    if ($printScreenState -eq 0) {
        
        Write-Host "< 3" -fore red      # heartbeat
        $WShell.sendkeys("{CAPSLOCK}")

        Start-Sleep -Milliseconds 200

        $WShell.sendkeys("{CAPSLOCK}")
        Write-Host "<3" -fore red       # heartbeat

        # Move mouse
        #$Pos = [System.Windows.Forms.Cursor]::Position; $Pos
        #$random = Get-Random -Minimum -100 -Maximum 100
        #$x = ($pos.X % 500) + $random
        #$y = ($pos.Y % 500) + $random
        #[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)

        Start-Sleep -Seconds $sleep
    }
    else {
        $TimeToQuit = $true
        Write-Output "Print Screen on, quitting"
    }
    
}while ($TimeToQuit -eq $false)

@IndieKid28
Copy link

Add-Type -AssemblyName System.Windows.Forms

while ($true)
{
$Pos = [System.Windows.Forms.Cursor]::Position
$x = ($pos.X % 500) + 1
$y = ($pos.Y % 500) + 1
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)
Start-Sleep -Seconds 10
}

I ended up running this script through powershell and now my pc won't sleep/screen won't turn off at all. Is there any way to undo this?

@quonic
Copy link

quonic commented Sep 21, 2023

Add-Type -AssemblyName System.Windows.Forms

while ($true) { $Pos = [System.Windows.Forms.Cursor]::Position $x = ($pos.X % 500) + 1 $y = ($pos.Y % 500) + 1 [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y) Start-Sleep -Seconds 10 }

I ended up running this script through powershell and now my pc won't sleep/screen won't turn off at all. Is there any way to undo this?

Close the powershell window. This is why I check for CapsLock, so when I press CapsLock it stops the script with ease.

@IndieKid28
Copy link

Add-Type -AssemblyName System.Windows.Forms
while ($true) { $Pos = [System.Windows.Forms.Cursor]::Position $x = ($pos.X % 500) + 1 $y = ($pos.Y % 500) + 1 [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y) Start-Sleep -Seconds 10 }
I ended up running this script through powershell and now my pc won't sleep/screen won't turn off at all. Is there any way to undo this?

Close the powershell window. This is why I check for CapsLock, so when I press CapsLock it stops the script with ease.

Thanks for the reply. In my case, when i run the script (right click and run with powershell) the window opens for a split second and then disappears, and it doesn't even show up in the task manager.

@quonic
Copy link

quonic commented Sep 21, 2023

Thanks for the reply. In my case, when i run the script (right click and run with powershell) the window opens for a split second and then disappears, and it doesn't even show up in the task manager.

Reboot. Then just use my code. When you press Caps Lock it will quit the script.

@IndieKid28
Copy link

IndieKid28 commented Sep 21, 2023

Thanks for the reply. In my case, when i run the script (right click and run with powershell) the window opens for a split second and then disappears, and it doesn't even show up in the task manager.

Reboot. Then just use my code. When you press Caps Lock it will quit the script.

Will this be detected by any monitoring app? Like powershell running or windows desktop runtime etc. ? Also your script doesn't seem to work for me. The screen keeps turning off regardless.

EDIT: strangely enough, the starting piece of code which was working earlier doesn't work anymore either.

@IndieKid28
Copy link

Use my script instead.

Are you sure the script is really what's holding up your shutdown? I do not believe it would.

Furthermore, are you sure the script is really running? Try opening PS as admin and running Set-ExecutionPolicy -ExecutionPolicy RemoteSigned CurrentUser (or LocalMachine). If that runs successfully, close PS and try again.

Will this be detected by any monitoring app? Like powershell running or windows desktop runtime etc. ? Also your script doesn't seem to work for me. The screen keeps turning off regardless.

The purpose of this script is not so you can sit AFK your entire day at work and pretend otherwise. It's so that when you go to the bathroom or whatever your VPN session doesn't lock on you, or when you talk to someone near your computer it doesn't lock on you. If your IT or whomever department "catches" you doing THAT, tell them to go to Hell.

Is this implementation mimicking mouse movement or is it just sending keystrokes? Because the sending keystrokes scripts don't seem to make me not show up as afk. I would need a mouse mover script.

@IndieKid28
Copy link

@AndrewDavis Who asked? Also judging by how you called someone a "retard" for suggesting something, I'm sure you're the last person to be taking life advices from lmao. Grow up clown.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment