How to send keyboard input only to a specific application

Viewed 384

I'm very new to Powershell. I wrote a simple script basically to automate grinding in a video game when I'm away from my computer. I wanted to know if there's a way instead to 'target' the button presses to a particular window/application/etc. while still working on the same machine in other windows. As it stands, I have to have the game window focused for the script to work so it's only really useful if I'm AFK. But if I could have it running in the background while working on other things that would be useful.

$WShell = New-Object -Com Wscript.Shell
while (1) {sleep 1; [System.Windows.Forms.SendKeys]::SendWait("{LEFT}"*80); 
[System.Windows.Forms.SendKeys]::SendWait("{RIGHT}"*80);sleep 1; 
[System.Windows.Forms.SendKeys]::SendWait("{C}"*20)}

Since I'm new to Powershell I'm not sure if this is doable or not. If not, it's no problem, this is a pretty frivolous use case, I was just curious.

1 Answers

Think about what you're currently doing. . .it's almost the same as tying the shoe laces on a pair of shoes, just to put on different ones;) You're not using the $wShell anywhere in your script.

. . .but, you're almost there already. We can start by loading the required assemblies, and then have it point to the application which you want to interact with:

Add-Type -AssemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms

[Microsoft.VisualBasic.Interaction]::AppActivate('Notepad')
Start-Sleep -Milliseconds 1000

[System.Windows.Forms.SendKeys]::SendWait("H")
Start-Sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("E")
Start-Sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("L")
Start-Sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("L")
Start-Sleep -Milliseconds 100
[System.Windows.Forms.SendKeys]::SendWait("O")

Take note of notepad in [Microsoft.VisualBasic.Interaction]::AppActivate('Notepad'), as it will be what ever program you're trying to interact with. In this case, you're just sending "HELLO" to the notepad that's already on started.

Related