I am Jakoby
I am Jakoby

Reputation: 617

powershell - pause script until mouse event detected OR key press detected

This first snippet creates a while loop that will pause a script until mouse movement is detected.

The second snippet pauses the script until a key is pressed.

They both work independently of each other but I am not confident on how to combine the two so the script is paused until EITHER mouse movement is detected or a key is pressed.

Add-Type -AssemblyName System.Windows.Forms
$originalPOS = [System.Windows.Forms.Cursor]::Position.X

while (1) {
    $newPOS = [System.Windows.Forms.Cursor]::Position.X
    if($newPOS -eq $originalPOS){
        Start-Sleep -Seconds 3
    }else {
        break
    }
}

SECOND SNIPPET

Write-Host -NoNewline 'Press any key'; $null = $host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')

Upvotes: 0

Views: 824

Answers (1)

marsze
marsze

Reputation: 17055

There are more sophisticated ways to detect mouse and keyboard input in PowerShell. But for your case, this might be sufficient.

while (1) {
    if ([Console]::KeyAvailable -or [Windows.Forms.Cursor]::Position.X -ne $originalPOS){
        break
    }
    else {
        Start-Sleep -Seconds 3
    }
}

Upvotes: 3

Related Questions