查看: 134  |  回复: 0
  VB6 通过管道命令获得CMD运行的结果
楼主
发表于 2024年10月2日 10:13

新建From1(窗体),新建Command1(按钮CommandButton),代码:

Private Sub s_ExecuteCommandAndGetOutput(command As String)
    Dim tempFile As String
    Dim fileNumber As Integer
    Dim commandOutput As String
    
    ' 创建一个临时文件名
    tempFile = App.Path & "\tempfile.txt"
    
    ' 打开文件用于输出重定向
    fileNumber = FreeFile()
    Open tempFile For Output As #fileNumber
    
    ' 使用管道将命令的输出重定向到文件
    Shell "cmd /c " & command & " > " & tempFile, vbHide
    
    ' 关闭文件
    Close #fileNumber
    
    ' 读取文件内容获取命令输出
    Open tempFile For Input As #fileNumber
    While Not EOF(fileNumber)
        Line Input #fileNumber, commandOutput
        ' 处理输出或者存储起来用于后续处理
        Debug.Print commandOutput
    Wend
    Close #fileNumber
    MsgBox "结果在 " & tempFile, vbInformation, "成功"
    
    ' 删除临时文件
    'Kill tempFile
End Sub

Private Sub Command1_Click()
    Dim strCmd As String
    strCmd = "dir *.*"
    Call s_ExecuteCommandAndGetOutput(strCmd)
End Sub


您需要登录后才可以回帖 登录 | 立即注册
【本版规则】请勿发表违反国家法律的内容,否则会被冻结账号和删贴。
用户名: 立即注册
密码:
2020-2024 MaNongKu.com