0

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')
spicy.dll
  • 948
  • 8
  • 23
I am Jakoby
  • 577
  • 4
  • 19
  • Does this answer your question? [How to capture global keystrokes with PowerShell?](https://stackoverflow.com/questions/54236696/how-to-capture-global-keystrokes-with-powershell) – marsze Nov 07 '21 at 08:41

1 Answers1

3

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
    }
}
marsze
  • 15,079
  • 5
  • 45
  • 61
  • ok so this works how I want if a console window is open. however if a console window is not open only the mouse movement detection works. the key press throws the following error: Cannot see if a key has been pressed when either application does not have a console or when console input has been redirected from a file. Try Console.In.Peak. Is there a way to get the key press detection to work with no console window up? – I am Jakoby Nov 06 '21 at 19:54