Win32APIのAllocConsole()のスクリプトバージョンみたいなものです。
VB6、EXCEL VBA、IE、HTA、WScriptなどのWindowsアプリから、
CScript.exeを起こして、コンソールを開き、コンソール入出力を行います。
以下は、Windowsアプリ側のサンプルです。
VBSファイルですが、VB/VBAのコードに貼り付けても使えます。
Set ie = CreateObject("InternetExplorer.Application")
Set wShell = CreateObject("WScript.Shell")
wShell.Run "CScript.exe ""CScript.VBS"" " & ie.Hwnd
For k = 1 To 10
If Not IsEmpty(ie.GetProperty("WScript")) Then
Set W = ie.GetProperty("WScript")
If TypeName(W) = "IHost_Class" Then Exit For
End If
' WScript.Sleep 100
' Application.Wait Now + TimeSerial(0, 0, 1)
wShell.Run "ping localhost -n 2",0,True
Next
'wShell.Popup TypeName(W) & vbTab, 5, "GetCScript", vbInformation
W.Echo "echo"
W.StdOut.WriteLine "stdout"
W.StdErr.WriteLine "stderr"
W.StdOut.Write "Enter stdin ? "
MsgBox W.StdIn.ReadLine, vbSystemModal, "GetCScript"
If vbYes = MsgBox("WScript.Quit ?" & vbTab, vbYesNo + vbQuestion, "GetCScript") Then W.Quit
MsgBox "Exit OK ?" & vbTab & vbTab, vbQuestion, "GetCScript"
'ie.Quit
[説明]
WScriptオブジェクトを受け渡しするために、IEを利用します。
IEはウィンドウハンドルで識別します。
CScript.exe側を起動します。
WSH以外での利用を想定してWScript.Sleep()をpingで代替しています。
WScriptオブジェクトをここでは変数[W]で受け取ります。
[WScript].Echo
[WScript].StdOut
[WScript].StdErr
[WScript].StdIn
などが使用できます。
[WScript].Quit
すると、CScript.exeは終了し、コンソールがすぐ閉じます。
Windowsアプリ側が終了してIEの参照を解放するか、IEを終了すると、
それをCScript.exe側が検知して、終了します。
この場合、コンソールを閉じる前にプロンプトします。
以下は、CScript.exeのWScriptオブジェクト(IHost_Class)を提供する部品側の
サンプルです。
CScript.VBS
Set Shell=CreateObject("Shell.Application")
For Each ie In Shell.Windows()
If ie.hwnd=CLng(WScript.Arguments.Item(0)) Then Exit For
Next
ie.PutProperty "WScript",WScript
Do While TypeName(ie)="IWebBrowser2"
WScript.Sleep 1000
Loop
MsgBox "Ended. Close OK ?"&vbTab,vbQuestion,WScript.ScriptName
WScript.StdOut.Write "Ended. Close OK ?"
WScript.StdIn.Read(1)
[説明]
Windowアプリ側に渡すため、WScriptオブジェクトをIEに渡します。
受け渡し用のIEが存在する間、待ち合わせをします。
Windowアプリ側が終了すると、IEが終了するので、抜けます。
コンソールがすぐ閉じないよう、MsgBoxかコンソールに問い合わせます。
これはどちらか選択してください。