VBGood网站全文搜索 Google

首页 - 经验之谈 - Finding the Associated Program
发表评论(0)作者:不详, 平台:VB6.0+Win98, 阅读:11446, 日期:2001-04-23
Finding the Associated Program

Looking to find the executable for a particular file extension? This code snippet has the answer.

Just pass it the extension - such as TXT or MDB - and it注释:ll return the associated Windows program.

It works by using the FindExecutable API call to locate the executable. However this requires an actual file with the requested extension, which is created with another couple of calls. The temporary file is deleted after the process has finished.

To use this code, call GetAssociatedExecutable, passing in the extension as a string.


x = GetAssociatedExecutable("MDB")Code

Private Declare Function FindExecutable Lib _
    "shell32.dll" Alias "FindExecutableA" _
    (ByVal lpFile As String, ByVal lpDirectory _
    As String, ByVal lpResult As String) As Long

Private Declare Function GetTempFileName Lib _
    "kernel32" Alias "GetTempFileNameA" (ByVal _
    lpszPath As String, ByVal lpPrefixString _
    As String, ByVal wUnique As Long, ByVal _
    lpTempFileName As String) As Long

Private Declare Function GetTempPath Lib _
    "kernel32" Alias "GetTempPathA" (ByVal _
    nBufferLength As Long, ByVal lpBuffer As _
    String) As Long

Public Function GetAssociatedExecutable(ByVal _
    Extension As String) As String

    Dim Path As String
    Dim FileName As String
    Dim nRet As Long
    Const MAX_PATH As Long = 260
    注释:Create a tempfile
    Path = String$(MAX_PATH, 0)
    If GetTempPath(MAX_PATH, Path) Then
        FileName = String$(MAX_PATH, 0)
        If GetTempFileName(Path, "~", 0, FileName) Then
            FileName = Left$(FileName, _
                InStr(FileName, vbNullChar) - 1)
            注释:Rename it to use supplied extension
            Name FileName As Left$(FileName, _
                InStr(FileName, ".")) & Extension
                FileName = Left$(FileName, _
                InStr(FileName, ".")) & Extension
            注释:Get name of associated EXE
            Path = String$(MAX_PATH, 0)
            Call FindExecutable(FileName, _
                vbNullString, Path)
            GetAssociatedExecutable = Left$( _
                Path, InStr(Path, vbNullChar) - 1)
            注释:Clean up
            Kill FileName
        End If
    End If

End Function