Cristian Malita
Cristian Malita

Reputation: 23

Powershell hangs on click event

I am new to powershell and I'm trying to write an autoclicker. So far I have this code:

Add-Type -MemberDefinition '[DllImport("user32.dll")] public static extern void mouse_event(int flags, int dx, int dy, int cButtons, int info);' -Name U32 -Namespace W;

function click {
    [W.U32]::mouse_event(2,0,0,0,0);
    [W.U32]::mouse_event(4,0,0,0,0);
}

$i = 10

while ($i -ge 0) {
    Write-Host "$i clicks remaining"
    Start-Sleep -m 1000
    click
    Write-Host "Clicked!"
    $i -= 1
}

The problem is that when I run the script it only performs the first click and then it just hangs.

The output is just:

10 clicks remaining

Only when I press Ctrl+C the script advances to the next iteration of the loop.

10 clicks remaining
Clicked!
9 clicks remaining

I simply don't understand what I'm doing wrong.

Upvotes: 2

Views: 1015

Answers (1)

mklement0
mklement0

Reputation: 437568

The problem is most likely that your mouse click accidentally suspends processing in the console window in which PowerShell is running if the mouse pointer happens to be over the console window's client area when you run the script.

(Left-)clicking on a console window puts it in select mode (for copying screen content to the clipboard) and that implicitly suspends the running shell / program; any keypress (other than a modifiers-only one) - such as Control-C in your case - exits this mode.

If you move the mouse pointer away from your console window and then launch your script, your script will run to completion.

Note that the clicks are then likely to activate a different window, and if that window overlaps the console window, the clicks will keep obscuring (part of) your console window. To eliminate that effect, hide all windows other than the console window first.

Upvotes: 2

Related Questions