[转载][VB6] 获取CMD命令的输出

在VB中不用文件(而用内存,再精确点是管道)来获取DOS程序的输出

方法:

1.新建工程
2.添加一个Class模块,命名为DOSOutputs,在Class内粘贴以下代码:

  1. Option Explicit
  2. ‘Class Module Named “DOSOutputs”
  3. ‘The CreatePipe function creates an anonymous pipe,
  4. ‘and returns handles to the read and write ends of the pipe.
  5. Private Declare Function CreatePipe Lib “kernel32” ( _
  6.     phReadPipe As Long, _
  7.     phWritePipe As Long, _
  8.     lpPipeAttributes As Any, _
  9.     ByVal nSize As Long) As Long
  10. ‘Used to read the the pipe filled by the process create
  11. ‘with the CretaProcessA function
  12. Private Declare Function ReadFile Lib “kernel32” ( _
  13.     ByVal hFile As Long, _
  14.     ByVal lpBuffer As String, _
  15.     ByVal nNumberOfBytesToRead As Long, _
  16.     lpNumberOfBytesRead As Long, _
  17.     ByVal lpOverlapped As Any) As Long
  18. ‘Structure used by the CreateProcessA function
  19. Private Type SECURITY_ATTRIBUTES
  20.     nLength As Long
  21.     lpSecurityDescriptor As Long
  22.     bInheritHandle As Long
  23. End Type
  24. ‘Structure used by the CreateProcessA function
  25. Private Type STARTUPINFO
  26.     cb As Long
  27.     lpReserved As Long
  28.     lpDesktop As Long
  29.     lpTitle As Long
  30.     dwX As Long
  31.     dwY As Long
  32.     dwXSize As Long
  33.     dwYSize As Long
  34.     dwXCountChars As Long
  35.     dwYCountChars As Long
  36.     dwFillAttribute As Long
  37.     dwFlags As Long
  38.     wShowWindow As Integer
  39.     cbReserved2 As Integer
  40.     lpReserved2 As Long
  41.     hStdInput As Long
  42.     hStdOutput As Long
  43.     hStdError As Long
  44. End Type
  45. ‘Structure used by the CreateProcessA function
  46. Private Type PROCESS_INFORMATION
  47.     hProcess As Long
  48.     hThread As Long
  49.     dwProcessID As Long
  50.     dwThreadID As Long
  51. End Type
  52. ‘This function launch the the commend and return the relative process
  53. ‘into the PRECESS_INFORMATION structure
  54. Private Declare Function CreateProcessA Lib “kernel32” ( _
  55.     ByVal lpApplicationName As Long, _
  56.     ByVal lpCommandLine As String, _
  57.     lpProcessAttributes As SECURITY_ATTRIBUTES, _
  58.     lpThreadAttributes As SECURITY_ATTRIBUTES, _
  59.     ByVal bInheritHandles As Long, _
  60.     ByVal dwCreationFlags As Long, _
  61.     ByVal lpEnvironment As Long, _
  62.     ByVal lpCurrentDirectory As Long, _
  63.     lpStartupInfo As STARTUPINFO, _
  64.     lpProcessInformation As PROCESS_INFORMATION) As Long
  65. ‘Close opened handle
  66. Private Declare Function CloseHandle Lib “kernel32” ( _
  67.     ByVal hHandle As Long) As Long
  68. ‘Consts for the above functions
  69. Private Const NORMAL_PRIORITY_CLASS = &H20&
  70. Private Const STARTF_USESTDHANDLES = &H100&
  71. Private Const STARTF_USESHOWWINDOW = &H1
  72. Private mCommand As String          ‘Private variable for the CommandLine property
  73. Private mOutputs As String          ‘Private variable for the ReadOnly Outputs property
  74. ‘This property set and get the DOS command line
  75. ‘It’s possible to set this property directly from the
  76. ‘parameter of the ExecuteCommand method
  77. Public Property Let CommandLine(DOSCommand As String)
  78.     mCommand = DOSCommand
  79. End Property
  80. Public Property Get CommandLine() As String
  81.     CommandLine = mCommand
  82. End Property
  83. ‘This property ReadOnly get the complete output after
  84. ‘a command execution
  85. Public Property Get Outputs()
  86.     Outputs = mOutputs
  87. End Property
  88. Public Function ExecuteCommand(Optional CommandLine As String) As String
  89.     Dim proc As PROCESS_INFORMATION     ’Process info filled by CreateProcessA
  90.     Dim ret As Long                     ’long variable for get the return value of the
  91.                                         ‘API functions
  92.     Dim start As STARTUPINFO            ’StartUp Info passed to the CreateProceeeA
  93.                                         ‘function
  94.     Dim sa As SECURITY_ATTRIBUTES       ‘Security Attributes passeed to the
  95.                                         ‘CreateProcessA function
  96.     Dim hReadPipe As Long               ’Read Pipe handle created by CreatePipe
  97.     Dim hWritePipe As Long              ’Write Pite handle created by CreatePipe
  98.     Dim lngBytesread As Long            ’Amount of byte read from the Read Pipe handle
  99.     Dim strBuff As String * 256         ’String buffer reading the Pipe
  100.     ‘if the parameter is not empty update the CommandLine property
  101.     If Len(CommandLine) > 0 Then
  102.         mCommand = CommandLine
  103.     End If
  104.     
  105.     ‘if the command line is empty then exit whit a error message
  106.     If Len(mCommand) = 0 Then
  107.         MsgBox “Command Line empty”, vbCritical
  108.         Exit Function
  109.     End If
  110.     
  111.     ‘Create the Pipe
  112.     sa.nLength = Len(sa)
  113.     sa.bInheritHandle = 1&
  114.     sa.lpSecurityDescriptor = 0&
  115.     ret = CreatePipe(hReadPipe, hWritePipe, sa, 0)
  116.     
  117.     If ret = 0 Then
  118.         ’If an error occur during the Pipe creation exit
  119.         MsgBox “CreatePipe failed. Error: “ & Err.LastDllError, vbCritical
  120.         Exit Function
  121.     End If
  122.     
  123.     ‘Launch the command line application
  124.     start.cb = Len(start)
  125.     start.dwFlags = STARTF_USESTDHANDLES Or STARTF_USESHOWWINDOW
  126.     ‘set the StdOutput and the StdError output to the same Write Pipe handle
  127.     start.hStdOutput = hWritePipe
  128.     start.hStdError = hWritePipe
  129.     ‘Execute the command
  130.     ret& = CreateProcessA(0&, mCommand, sa, sa, 1&, _
  131.         NORMAL_PRIORITY_CLASS, 0&, 0&, start, proc)
  132.         
  133.     If ret <> 1 Then
  134.         ’if the command is not found ….
  135.         MsgBox “File or command not found”, vbCritical
  136.         Exit Function
  137.     End If
  138.     
  139.     ‘Now We can … must close the hWritePipe
  140.     ret = CloseHandle(hWritePipe)
  141.     mOutputs = “”
  142.     
  143.     ‘Read the ReadPipe handle
  144.     Do
  145.         ret = ReadFile(hReadPipe, strBuff, 256, lngBytesread, 0&)
  146.         mOutputs = mOutputs & StrConv(LeftB((StrConv(strBuff, vbFromUnicode)), lngBytesread), vbUnicode)
  147.         
  148.         ’原来为 mOutputs = mOutputs & Left(strBuff, lngBytesread),感谢mr_gjd 提供关键性修改!
  149.     Loop While ret <> 0
  150.     
  151.     ‘Close the opened handles
  152.     ret = CloseHandle(proc.hProcess)
  153.     ret = CloseHandle(proc.hThread)
  154.     ret = CloseHandle(hReadPipe)
  155.     
  156.     ‘Return the Outputs property with the entire DOS output
  157.     ExecuteCommand = mOutputs
  158. End Function

3.在窗体内添加两个TextBox:txtCmdInputtxtDosOutput并将后者的MultiLine属性改为True
4.在窗体内粘贴以下的代码



  1. Option Explicit
  2. 'Form's Code
  3. Private Sub Form_Load()
  4.   txtCmdInput.Text = "dir c:\"
  5.   txtCmdInput_KeyPress vbKeyReturn
  6. End Sub

  7. Private Sub txtCmdInput_KeyPress(KeyAscii As Integer)
  8.   Dim objDOS As DOSOutputs
  9.   
  10.   If KeyAscii = vbKeyReturn Then Exit Sub
  11.   Set objDOS = New DOSOutputs
  12.   objDOS.CommandLine = "cmd.exe /c " & txtCmdInput.Text
  13.   objDOS.ExecuteCommand
  14.   txtDosOutput.Text = Replace(objDOS.Outputs, Chr(0), "")
  15.   txtCmdInput.SelStart = 0
  16.   txtCmdInput.SelLength = Len(txtCmdInput.Text)
  17. End Sub

5.运行!

注:直接复制可能会有错误,建议直接下载(点击链接下载~)
**
**

  CMD输出到VB.zip

« [原创][VB6] 又是一个整人小程序 - Desktop Spammer [转载][Chrome套件] Chrome Remote Desktop 连线遥控他人的电脑! »
comments powered by Disqus