LoginSignup
1
1

More than 3 years have passed since last update.

PowerShellでキーボードマクロ書いた。

Last updated at Posted at 2021-05-19

これ何

なんでもキーボードマクロ送れる奴。

どうやって使うの

キーボードマクロ送りたいソフトの同じディレクトリに置いて
$script:TargetFileにターゲットの実行ファイル名を拡張子無しで"notepad"みたいに書く。
$script:Macrosは送りたいキーコードをステップ毎に,で区切って@("test1","test2")みたいに書く。
$script:StartWaitこれはもしソフトが起動していないときに起動するけどマクロ受け付けるまで待ち時間が生じるときのために待ち時間を設ける数値、単位はms(ミリセカンド)。

ちょっとややこしいやつ

これの設定$script:Waitちょっと理解しづらいかもしれない。ステップごとのウェイト時間を書く。単位はms。
操作後のラグなどで待ち時間が必要なときのためにウェイトを設けたい時が有ったりすると思う。そんなときはステップを分けてあげればいい。キーボードマクロは配列として設定するので@()の中に,で区切ってステップを記述する。各ステップは""で囲う。ステップの書き方はMSDN:SendKeysを参考にしてください。

コード

#Auto-Macro by Fizz

#references https://qiita.com/nimzo6689/items/488467dbe0c4e5645745

#paramater
param(
    $script:RootDirectory = (Split-Path $MyInvocation.MyCommand.path),
    $script:TargetFile = "notepad",
    $script:Macros = @("test1","test2"),
    $script:StartWait = 3000,
    $script:Wait = 1000
)

#declare assembly
Add-Type -AssemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms

#main
function main{
    $pobj = GetProcessObject $script:TargetFile
    if($null -eq $pobj){
        try{
            Start-Process -FilePath $(GetFilePath $script:TargetFile "exe")
            Start-Sleep -m $script:StartWait
            $pobj = GetProcessObject $script:TargetFile
        }catch{
            Pause
            throw
        }
    }
    AppActivate $pobj
    SendKeysMacro $script:Macros
}

#functions
function GetFilePath($filename,$extention){
    $fn = $filename + "." + $extention
    return $(Join-Path -Path $script:RootDirectory -ChildPath $fn -Resolve)
}

function SendKeysMacro($macros){
    foreach($command in $macros){
        Start-Sleep -m $script:Wait
        [System.Windows.Forms.SendKeys]::SendWait($command)
    }
}

function AppActivate($pobj){
    [Microsoft.VisualBasic.Interaction]::AppActivate($pobj.ID)
}

function GetProcessObject($name){
    return (Get-Process $name | Where-Object {$_.MainWindowTitle -ne ""})
}

#entry
main

参考

https://docs.microsoft.com/ja-jp/previous-versions/windows/scripting/cc364423(v=msdn.10)?redirectedfrom=MSDN
https://qiita.com/nimzo6689/items/488467dbe0c4e5645745

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1