« WScript.ShellのExec()で、コンソールアプリを非表示で実行するラッパー(その2) | トップページ | コンソールアプリを非表示で実行するラッパーをVB.NETで作る。(その2) »

2008年8月25日 (月)

コンソールアプリを非表示で実行するラッパーをVB.NETで作る。

ウィンドウアプリとしてコンパイルします。

vbc /t:winexe HideExec.VB

Imports Microsoft.VisualBasic
Imports System
Imports System.Diagnostics
Imports System.Threading
Imports System.Text
Imports System.IO

Public Class HideExec

Private Shared InputWriter As StreamWriter = Nothing
Private Shared OutputReader As StreamReader = Nothing
Private Shared ErrorReader As StreamReader = Nothing

Public Shared Function Main(ByVal Arguments() As String) As Integer
Dim CommandLine As String = System.Environment.CommandLine
Dim FileName As String = ""
Dim n As Integer
For n = 1 To 2
  Dim Quoted As Boolean = False
  Dim k As Integer
  For k=0 To CommandLine.Length-1
    If CommandLine.Chars(k) = """" Then
      Quoted = Not Quoted
    ElseIf Not Quoted AndAlso CommandLine.Chars(k) = " " Then
      Exit For
    End If
  Next
  FileName = CommandLine.Substring(0,k).Replace("""","")
  CommandLine = CommandLine.Remove(0,k).Trim()
'  Console.WriteLine("FileName:{0}",FileName)
'  Console.WriteLine("Arguments:{0}",CommandLine)
Next
Dim oProcess As New Process()
oProcess.StartInfo.FileName = FileName
oProcess.StartInfo.Arguments = CommandLine
oProcess.StartInfo.UseShellExecute = False
oProcess.StartInfo.CreateNoWindow = True
oProcess.StartInfo.RedirectStandardInput = True
oProcess.StartInfo.RedirectStandardOutput = True
oProcess.StartInfo.RedirectStandardError = True

Try
  oProcess.Start()
  OutputReader = oProcess.StandardOutput
  Dim OutputThread As New Thread(AddressOf OutputDataHandler)
  OutputThread.Start()
  ErrorReader = oProcess.StandardError
  Dim ErrorThread As New Thread(AddressOf ErrorDataHandler)
  ErrorThread.Start()
  InputWriter = oProcess.StandardInput
  Dim InputThread As New Thread(AddressOf InputDataHandler)
  InputThread.Start()
  oProcess.WaitForExit()
  OutputThread.Join()
  ErrorThread.Join()
  System.Environment.Exit(oProcess.ExitCode)
Catch
  MsgBox("Source" & vbTab & vbTab & Err.Source & vbLf & "Number" & vbTab & vbTab & Err.Number & vbLf & "Description" & vbTab & Err.Description & vbLf & "DLL Error" & vbTab & vbTab & Err.LastDLLError)
  System.Environment.Exit(255)
End Try
End Function

Private Shared Sub OutputDataHandler()
Do
  Dim c As Integer = OutputReader.Read()
  If c = -1 Then Exit Do
  Console.Write(Convert.ToChar(c))
Loop
End Sub

Private Shared Sub ErrorDataHandler()
Do
  Dim c As Integer = ErrorReader.Read()
  If c = -1 Then Exit Do
  Console.Error.Write(Convert.ToChar(c))
Loop
End Sub

Private Shared Sub InputDataHandler()
Try
  Do
    Dim c As Integer = Console.Read()
    If c = -1 Then Exit Do
    InputWriter.Write(Convert.ToChar(c))
  Loop
Catch
End Try
InputWriter.Close()
End Sub

End Class

« WScript.ShellのExec()で、コンソールアプリを非表示で実行するラッパー(その2) | トップページ | コンソールアプリを非表示で実行するラッパーをVB.NETで作る。(その2) »