下面是一个打开指定文件的函数,用到了API函数FindExecutable、CreateProcess和ShellExecute,需要注意的是,通过FindExecutable找到的关联文件字符串strResult在返回时,后面会有很多null(asc=0),不把这些null去掉就无法打开指定的文件,只会打开一个空的文件,所以要写一个专门去掉null的函数,不知道VB里面有没有这样的函数 :)。
Public Function GF_lSpawn(ByVal sFileName As String, Optional ByVal bWait As Boolean = True) As Long
Dim strResult As String * 260
Dim lResult As Long
Dim start As STARTUPINFO
Dim proc As PROCESS_INFORMATION
Dim rc As Long
Dim strCommandLine As String
On Error GoTo ErrProc
lResult = FindExecutable(sFileName, "", strResult)
If Asc(Left(strResult, 1)) = 0 Then
MsgBox "没有可以打开" & sFileName & "文件的软件!"
Exit Function
End If
If bWait Then
start.cb = Len(start)
start.lpReserved = vbNullString
start.cbReserved2 = 0
start.lpReserved2 = 0
strCommandLine = My_Trim(strResult) + " " + My_Trim(sFileName)
rc = CreateProcess(vbNullString, strCommandLine, ByVal 0, ByVal 0, False, NORMAL_PRIORITY_CLASS, ByVal 0, vbNullString, start, proc)
rc = WaitForSingleObject(proc.hThread, INFINITE)
rc = CloseHandle(Proc.hThread)
Else
ShellExecute 0, "open", strFileName, "", "", SW_SHOWNORMAL
End If
GF_lSpawn = rc
Exit Function
ErrProc:
GF_lSpawn = 0
MsgBox "打开文件出错,错误信息:" + Err.Description
End Function
Public Function My_Trim(ByVal strSrc As String) As String
Dim i As Integer
Dim str As String
Dim strDesc As String
str = ""
strDesc = ""
For i = 1 To Len(strSrc)
str = Mid(strSrc, i, 1)
If Asc(str) <> 0 Then
strDesc = strDesc + str
End If
Next i
My_Trim = strDesc
End Function