LoginSignup
14
21

More than 5 years have passed since last update.

PowerShellでアクティブウィンドウをキャプチャ

Last updated at Posted at 2017-10-11

Powershellでアクティブウィンドウをキャプチャ

あるプログラムで繰り返しのテストを行っていたのですが、
自動化をするにあたってPowerShellを利用しました。
その際にキャプチャのやり方が分かったので載せておきます。

コード

例としてメモ帳をキャプチャします。

capture_note.ps1
#キャプチャ関数
function Get-ScreenCapture($name)
{   
    begin {
        Add-Type -AssemblyName System.Drawing, System.Windows.Forms
        $jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | 
            Where-Object { $_.FormatDescription -eq "JPEG" }
    }
    process {
        Start-Sleep -Milliseconds 250

        #Alt+PrintScreenを送信
        [Windows.Forms.Sendkeys]::SendWait("%{PrtSc}")        

        Start-Sleep -Milliseconds 250

        #クリップボードから画像をコピー
        $bitmap = [Windows.Forms.Clipboard]::GetImage()    

        #画像保存(名前がかぶらないようにしている)
        $ep = New-Object Drawing.Imaging.EncoderParameters  
        $ep.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, [long]100)
        $screenCapturePathBase = "$env:USERPROFILE\Desktop\${name}"
        $c = 0
        while (Test-Path "${screenCapturePathBase}_${c}.jpg") {
            $c++
        }
        $bitmap.Save("${screenCapturePathBase}_${c}.jpg", $jpegCodec, $ep)
    }
}

#例としてメモ帳起動
notepad

#起動完了まで待つ
Start-Sleep -Milliseconds 500

#とりあえずtestを送信
#$retは使用していないがMarkdownでうまく表示されないため追加
$ret = [Windows.Forms.Sendkeys]::SendWait("test")


#キャプチャ
Get-ScreenCapture test

#メモ帳終了
$ret = [System.Windows.Forms.SendKeys]::SendWait("%{F4}")
Start-Sleep -Milliseconds 500
$ret = [System.Windows.Forms.SendKeys]::SendWait("{TAB}")
start-sleep -Milliseconds 500
$ret = [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")

実行結果

スクリプトを実行します。

.\capture_note.ps1

次の画像が無事にキャプチャされました。
test_0.jpg
しょうもないですが、何かと組み合わせたりすると役に立つかもしれません。

14
21
2

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
14
21