利用VB的Shell执行PING命令,将PING的输出重定向到文件 c:\r.txt,然后读取c:\r.txt文件显示运行结果。
由于VB中的Shell命令是异步执行的,即调用Shell后,没等Shell执行完毕,程序就继续执行下一条语句。为此,程序使用了系统API来判断Shell是否结束。
1)窗体及控件
Private Declare Function GetExitCodeProcess Lib "kernel32" ( _
ByVal hProcess As Long, _
lpExitCode As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" ( _
ByVal hObject As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" ( _
ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Const PROCESS_QUERY_INFORMATION = &H400
Const STILL_ALIVE = &H103
Private Sub Command1_Click()
If Trim(Text1.Text) = "" Then
MsgBox "请输入域名或IP地址", vbInformation + vbOKOnly
Text1.SetFocus
Exit Sub
End If
'命令执行期间禁用命令按钮
Command1.Enabled = False
'调用Shell执行Ping,执行结果重定向到C:\r.txt中
Dim pid As Long
pid = Shell("cmd.exe /C Ping " & Text1.Text & " > c:\r.txt", vbHide)
' 提示
Text2.Text = "正在执行Ping " & Text1.Text & " ..."
'等待Shell执行结束
Dim hProc As Long
hProc = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid)
Dim ExitCode As Long
Do
Call GetExitCodeProcess(hProc, ExitCode)
DoEvents
Loop While ExitCode = STILL_ALIVE
'清空,准备显示结果
Text2.Text = ""
'打开 C:\r.txt文件
Open "c:\r.txt" For Input As #1
Dim strLine As String
Do Until EOF(1)
Line Input #1, strLine
'显示执行结果
Text2.Text = Text2.Text & strLine & vbNewLine
Loop
'关闭文件
Close #1
'删除C:\r.txt
On Error Resume Next
Kill "c:\r.txt"
On Error GoTo 0
'使能命令按钮
Command1.Enabled = True
End Sub
Private Sub Form_Load()
Text1.Text = ""
Text2.Text = ""
End Sub
3)运行结果
Ping baidu.com 正在执行中 ....
Ping baidu.com执行结果