以默认程序打开文档
要以与文件后缀名关联的程序打开文档,在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"