powershell mouse move does not prevent idle mode

nivoe picture nivoe · Apr 5, 2013 · Viewed 97.5k times · Source

Before I start, here is my very first little code I wrote in PowerShell :)

[System.Windows.Forms.Cursor]::Position = `
    New-Object System.Drawing.Point($pos.X, ($pos.Y - 1))
[System.Windows.Forms.Cursor]::Position = `
    New-Object System.Drawing.Point($pos.X, $pos.Y)

What do I want to achieve?

Well, I want to move the mouse cursor every 4 minutes to prevent the screensaver from appearing (every second in the code above for testing). The code does really move the mouse every time one pixel up and then down immediately. The thing is, the screensaver (or idle mode of windows) is still appearing.

Now, I am learning PowerShell and I have little experience with the Windows architecture.

Does anybody see my mistake? I would appreciate an answer a lot! :D Thanks in advance.

Answer

JPBlanc picture JPBlanc · Apr 6, 2013

The solution from the blog Prevent desktop lock or screensaver with PowerShell is working for me. Here is the relevant script, which simply sends a single period to the shell:

param($minutes = 60)

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

for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 60
  $myshell.sendkeys(".")
}

and an alternative from the comments, which moves the mouse a single pixel:

$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + 1) , $Pos.Y)
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) - 1) , $Pos.Y)