早速の返信ありがとうございます。
おかげさまで以下のコードで実現できて助かりました。
これから少しづつ学んでいこうと思います。
ありがとうございました。
Using p As New Process
p.StartInfo.FileName = Environment.GetEnvironmentVariable("ComSpec")
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.RedirectStandardInput = False
p.StartInfo.CreateNoWindow = True
p.StartInfo.Arguments = "/c ping 127.0.0.1"
p.Start()
Dim reader = p.StandardOutput
Do Until reader.EndOfStream
Dim buffer = reader.ReadLine()
'以下3行を追加
Debug.Print(buffer)
TextBox1.Text = TextBox1.Text & vbCrLf & buffer
Me.Refresh()
Loop
p.WaitForExit()
End Using
2023/08/23(Wed) 05:57:00 編集(投稿者)
■No35497に返信(ぱんださんの記事)
CTRL+C を送ってキャンセルでいいんですかね?
Imports System.Runtime.InteropServices
Public Class Form1
Private cmdProcess As Process
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If cmdProcess IsNot Nothing Then Return
TextBox1.Clear()
cmdProcess = New Process
cmdProcess.StartInfo.FileName = Environment.GetEnvironmentVariable("ComSpec")
cmdProcess.StartInfo.UseShellExecute = False
cmdProcess.StartInfo.RedirectStandardOutput = True
cmdProcess.StartInfo.RedirectStandardInput = False
cmdProcess.StartInfo.CreateNoWindow = True
cmdProcess.StartInfo.Arguments = "/c " & TextBox2.Text
cmdProcess.Start()
Task.Run(AddressOf ReadTask)
Button1.Enabled = False
Button2.Enabled = True
End Sub
Private Sub ReadTask()
Dim reader = cmdProcess.StandardOutput
Do Until reader.EndOfStream
Dim buffer = reader.ReadLine()
Invoke(Sub()
TextBox1.AppendText(vbCrLf & buffer)
Refresh()
End Sub)
Loop
cmdProcess.WaitForExit()
cmdProcess.Dispose()
cmdProcess = Nothing
Invoke(Sub()
Button1.Enabled = True
Button2.Enabled = False
End Sub)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If AttachConsole(cmdProcess.Id) Then
SetConsoleCtrlHandler(IntPtr.Zero, True)
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)
cmdProcess.WaitForExit()
SetConsoleCtrlHandler(IntPtr.Zero, False)
FreeConsole()
End If
End Sub
Private Const CTRL_C_EVENT = 0
Private Const CTRL_BREAK_EVENT = 1
<DllImport("Kernel32")>
Private Shared Sub GenerateConsoleCtrlEvent(dwCtrlEvent As Integer, dwProcessGroupId As Integer)
End Sub
<DllImport("Kernel32")>
Private Shared Function AttachConsole(dwProcessId As Integer) As Boolean
End Function
<DllImport("Kernel32")>
Private Shared Function SetConsoleCtrlHandler(HandlerRoutine As IntPtr, add As Boolean) As Boolean
End Function
<DllImport("Kernel32")>
Private Shared Function FreeConsole() As Boolean
End Function
End Class