Monday, January 15, 2007

在 VB 中同步等待執行的結果

Public Function SyncExecute(ByVal szProgram As String, ByVal szCommandLine As String, Optional ByVal fRedirectOutput) As String

Dim hProcess As Long
Dim hFile As Long
Dim si As STARTUPINFO
Dim pi As PROCESS_INFORMATION
Dim ps As SECURITY_ATTRIBUTES
Dim ts As SECURITY_ATTRIBUTES
Dim sTempFile As String
Dim bResult As Long

On Error GoTo ErrHandler:
SyncExecute = ""
If IsMissing(fRedirectOutput) Then
fRedirectOutput = False
End If

' If redirection needed executes program
sTempFile = GetTempFile
If fRedirectOutput Then
si.cb = Len(si)
si.dwFlags = STARTF_USESTDHANDLES Or STARTF_USESHOWWINDOW
si.wShowWindow = SW_HIDE

' Creates a temp file
hFile = CreateFile(sTempFile, GENERIC_READ Or GENERIC_WRITE, _
0, ByVal 0&, CREATE_ALWAYS, 0, ByVal 0&)
If hFile Then
si.hStdOutput = hFile
End If
End If

' Creates the process
'bResult = CreateProcess(szProgram, szCommandLine, _
ByVal 0&, ByVal 0&, True, NORMAL_PRIORITY_CLASS, _
ByVal 0&, vbNullString, si, pi)
ps.nLength = Len(ps)
ts.nLength = Len(ts)
bResult = CreateProcess(szProgram, szCommandLine, _
ps, ts, True, NORMAL_PRIORITY_CLASS, _
ByVal 0&, vbNullString, si, pi) ' CREATE_NEW_CONSOLE
If bResult Then
WaitForSingleObject pi.hProcess, INFINITE
End If

' Closes handles
If hFile And fRedirectOutput Then
Dim numOfBytes As Long
Dim buf As String
numOfBytes = GetFileSize(hFile, ByVal 0&)
buf = Space(numOfBytes)
CloseHandle (hFile)

' Reads back the file content
hFile = lopen(sTempFile, 0)
lread hFile, buf, numOfBytes
lclose (hFile)

' Returns
SyncExecute = buf
DeleteFile (sTempFile)
End If
Exit Function
ErrHandler:
Call LogError("[SyncExecute] Command = " & szCommandLine & ", Err = " & _
Err.Number & ", Source = " & Err.Source & ", " & Err.Description)
End Function

0 Comments:

Post a Comment

<< Home