@tk0805

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

PowerShellでSendKeysによるキー入力処理が動作しないPC端末が

解決したいこと

PowerShellでキー入力を自動化する処理を作成したのですが、一部端末でキー入力処理が実施されないPCが出ているため、キー入力処理が正常に実行されるよう修正したいのですが、原因が掴めず質問した次第です。
(基本的には正常動作するが、一部PCでキー入力が実施されない状況)

発生している問題・エラー

以下のソースコードは問題調査用のサンプルプログラムです。
メモ帳を開いて「aiueo」と入力する処理になっています。
一部PCでは、この処理を実行しても、メモ帳は起動するが、「aiueo」は入力されずにプログラムが終了してしまいます。(エラーメッセージ等も出ません。)

該当するソースコード

#System.Windows.Formsのインポートを行う
add-type -AssemblyName System.Windows.Forms

#メモ帳を開く
notepad

#500ミリ秒スリープ
start-sleep -Milliseconds 500

#aiueoと入力
[System.Windows.Forms.SendKeys]::SendWait("aiueo")
0 likes

2Answer

notepadのハンドルを取得しアクティブにすると確実です。

add-type -AssemblyName System.Windows.Forms
notepad
start-sleep -Milliseconds 500
$nProc = Get-Process -Name notepad
if ($nProc) {
    $nHand = $nProc.MainWindowHandle [System.Windows.Forms.NativeMethods]::SetForegroundWindow($nHand)
}
[System.Windows.Forms.SendKeys]::SendWait("aiueo")

Add-Type -TypeDefinition @'
  ....
'@

$process = Start-Process -FilePath "notepad.exe" -PassThru
if ($process) {
[User32]::SetForegroundWindow($process.MainWindowHandle)
}
1Like

Comments

  1. @tk0805

    Questioner

    サンプルコードまで記述いただき、ありがとうございます。
    問題となるPCが手元にないのですぐには試せないのですが、後日、上記のコードで動作確認してみます。

Your answer might help someone💌