Rayshawn
Rayshawn

Reputation: 2617

How to send keystroke to executable?

How can I enter a keystroke programmatically through a PowerShell script?

Write-Host -ForegroundColor Green 'Loading...'

Function EnterKey {
  [Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
  #Where I want to get "|" keystroke programmatically
  [System.Windows.Forms.SendKeys]::SendWait("{|}")
}

Function StartUp {
  Write-Host "Environment"

  $exe = ([IO.Path]::Combine("D:\7ZipApp\7ZipApp\7ZipApp\bin\Debug","7ZipApp.exe"))
  & $exe 3 # argument 3 = 'Run local Sync'
  EnterKey
  Read-Host -Prompt $exe.ToString()
}

StartUp

Upvotes: 1

Views: 2649

Answers (2)

Kory Gill
Kory Gill

Reputation: 7153

I have to go with the crowd here (from the comments):

I would abandon your approach. Too problematic.

My question was why you want to do it

The correct solution, then, is to get the author of 7zipapp.exe to fix the program so it stops doing that or to add a command-line parameter that prevents this behavior.

That said, if you want a total hack, and this program only takes ONE input, at the end presumably, then the below appears to work. I would use sparingly, perhaps never use it, but rather get the program fixed, but in my testing, this worked.

PowerShell:

$exe = 'C:\ConsoleApplication2\bin\Debug\ConsoleApplication2.exe'
'\r\n' | & $exe

Annoying C# program:

using static System.Console;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("I will force you to hit Enter to exit.");
            ReadLine();
        }
    }
}

Upvotes: 1

Anthony Stringer
Anthony Stringer

Reputation: 2001

Write-Host -ForegroundColor Green 'Loading...'

function StartUp {
    Write-Host 'Environment'

    $exe = Join-Path "D:\7ZipApp\7ZipApp\7ZipApp\bin\Debug" "7ZipApp.exe"
    #& $exe 3 # argument 3 = 'Run local Sync'
    start $exe -ArgumentList 3

    Write-Host 'Type {|} to continue'
    while ((Read-Host) -ne '{|}') {}

    Read-Host -Prompt $exe.ToString()
}

StartUp

Upvotes: 1

Related Questions