以默認程序打開文檔
要以與文件后綴名關聯的程序打開文檔,在Windows 9X和Windows NT下可以用ShellExcute函數方便地實現。這則小技巧展示了會有多方便—你只需要一個聲明和一行代碼!
開始一個新項目。在Form上放一個Command button,然后加入以下代碼:
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hWnd As Long, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, _
ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Private Const SW_NORMAL=1 '(這些API常量可以用VB常量代替,比如vbNormalFocus)
Private Const SW_MAXIMIZE=3
Private Const SW_MINIMIZE=6
Private Const SW_SHOW = 5
Private Sub Command1_Click()
Dim lR As Long
Dim sFile As String
Dim iFile As Integer
' 創建一個測試用的文本文件
sFile = App.Path & "\SHELLTST.TXT"
On Error Resume Next
Kill sFile
On Error GoTo 0
iFile = FreeFile
Open sFile For Binary Aclearcase/" target="_blank" >ccess Write As #iFile
Put #iFile, , "這是一個測試文件,演示ShellExecute API函數。"
Close #iFile
' 依照文件名打開這個文本。Windows將會檢查哪個可執行程序與.TXT關聯
' (默認一般是Notepad),并運行程序打開文檔
lR = ShellExecute(Me.hWnd, "Open", sFile, "", "", vbNormalFocus)
If (lR < 0) Or (lR > 32) Then
' 成功
Else
MsgBox "無法打開 '" & sFile & "'", vbInformation
End If
End Sub
當你點擊command button,將會在項目所在目錄創建一個文本文件,并用默認程序打開(一般是Notepad)。
===============================================
譯者附:
本函數還可以用來連接到網頁,照下面寫就行了:
ShellExecute 0&, vbNullString, "http://coolbasic.yeah.net", vbNullString, vbNullString, vbNormalFocus
或者這樣寫來發送Email:
ShellExecute me.hwnd, "open", "mailto:vbcode@vbcode.com", vbNullString, vbNullString, SW_SHOW
另外有ShellExecute的替代用法,更加簡單實用,不用API,一句Shell搞定!
連接到網頁:
Shell "rundll32.exe url.dll,FileProtocolHandler http://www.online.sh.cn"
打開文件:
Shell "rundll32.exe url.dll,FileProtocolHandler " & App.Path & "\SHELLTST.TXT"