CreateObjectの2番目のパラメーターを使用すると、IEイベントに応答するスクリプトを作成できます。IEは、ウィンドウが閉じられたときに発生するonQuitイベントを公開します。CreateObjectメソッドのWScriptバリアントを指定していることを確認してください。ネイティブVBScriptは、必要な2番目のパラメーターをサポートしていません。
Set objIE = WScript.CreateObject("InternetExplorer.Application", "IE_")
' Set up IE and navigate to page
' ...
' Keep the script busy so it doesn't end while waiting for the IE event
' It will start executing inside the subroutine below when the event fires
Do While True
WScript.Sleep 1000
Loop
' Execute code when IE closes
Sub IE_onQuit
'Do something here
End Sub
この方法の詳細については、こちらのより詳細な例をご覧ください。これは優れた非同期ソリューションです。
2番目の方法では、WMIを使用してIEを起動し、実行中のインスタンスへの直接オブジェクトを取得します。インスタンスが閉じられると、オブジェクト参照はnullになります。
Const SW_NORMAL = 1
strCommandLine = "%PROGRAMFILES%\Internet Explorer\iexplore.exe"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objProcessStartup = objWMIService.Get("Win32_ProcessStartup")
Set objStartupInformation = objProcessStartup.SpawnInstance_
objStartupInformation.ShowWindow = SW_NORMAL
objStartupInformation.Title = strUniqueTitle
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
intReturn = objProcess.Create("cmd /k" & vbQuote & strCommandLine & vbQuote, null, objStartupInformation, intProcessID)
Set objEvents = objWMIService.ExecNotificationQuery( _
"SELECT * FROM __InstanceDeletionEvent " & _
"WHERE TargetInstance ISA 'Win32_Process' " & _
"AND TargetInstance.PID = '" & intProcessID & "'")
' The script will wait here until the process terminates and then execute any code below.
Set objReceivedEvent = objEvents.NextEvent
' Code below executes after IE closes
このソリューションは、WMIを使用してプロセスインスタンスを開始し、そのプロセスIDを返します。次に、WMIイベントを使用して、プロセスが終了するのを監視します。これは同期メソッドであり、スクリプトの実行は停止し、プロセスが完了するまで待機します。これはメソッドと非同期で実行することもできますExecNotificationQueryAsync
が、このタイプのスクリプトはあまり一般的ではありません。