请问在VB中,如何获取一个快捷方式(.lnk文件)的目标路径。 
或者能否介绍一下.lnk文件的结构

解决方案 »

  1.   

    用 Windows API 做不到;而 VB 又不能使用 COM 接口,好像比较困难。
    如果有 .LNK 文件的结构好像可以解决(也不一定,而且 Windows 各个版本的可能有不同的 .LNK 结构)。
      

  2.   

    用OPEN对话框就能嘛,API好象也行!
      

  3.   

    我有例子,要的话留下Email!!加分!!
      

  4.   

    把以下代码存为Shelllnk.odl,编译成Shelllnk.tlb                        // Default Win95[ANSI]
    //#define UNICODE //         WinNT[UNICODE][
    #ifdef UNICODE
        uuid(11269240-F241-11cf-BD9A-00AA00575603),
        helpstring("IShellLinkW Interface"),
    #else
        uuid(11269241-F241-11cf-BD9A-00AA00575603),
        helpstring("IShellLinkA Interface"),
    #endif
        version(1.0)
    ]
    #ifdef UNICODE
        library IShellLinkW
        #define ISTRING LPWSTR
    #else
        library IShellLinkA
        #define ISTRING LPSTR
    #endif
    #define TCHAR unsigned char{
        importlib("stdole2.tlb");    #define MAX_PATH  255    typedef struct FILETIME
        {
          long  dwLowDateTime;
          long  dwHighDateTime;
        } FILETIME;    typedef struct WIN32_FIND_DATA
        {
          long      dwFileAttributes;
          FILETIME  ftCreationTime;
          FILETIME  ftLastAccessTime;
          FILETIME  ftLastWriteTime;
          long      nFileSizeHigh;
          long      nFileSizeLow;
          long      dwReserved0;
          long      dwReserved1;
          TCHAR     cFileName[MAX_PATH];
          TCHAR     cAlternate[14];
        } WIN32_FIND_DATA;    // IShellLink::Resolve fFlags
        typedef enum {
            SLR_NO_UI           = 0x0001,
            SLR_ANY_MATCH       = 0x0002,
            SLR_UPDATE          = 0x0004,
        } SLR_FLAGS;    // IShellLink::GetPath fFlags
        typedef enum {
            SLGP_SHORTPATH      = 0x0001,
            SLGP_UNCPRIORITY    = 0x0002,
        } SLGP_FLAGS;    //==========================================================================
        [
            uuid(0000010b-0000-0000-C000-000000000046),
            helpstring("IPersistFile Interface"),
            odl
        ]
        //==========================================================================
        interface IPersistFile : IUnknown
        //==========================================================================
        {
            [helpstring("GetClassID")]
            HRESULT GetClassID (
                            [in,out] long  *pClassID);        [helpstring("IsDirty")]
            HRESULT IsDirty (void);        [helpstring("Load")]
            HRESULT Load (
                            [in]     LPSTR  pszFileName,
                            [in]     long   dwMode);        [helpstring("Save")]
            HRESULT Save (
                            [in]     LPSTR  pszFileName,
                            [in]     long   fRemember);        [helpstring("SaveCompleted")]
            HRESULT SaveCompleted (
                            [in]     LPSTR  pszFileName);        [helpstring("GetCurFile")]
            HRESULT GetCurFile (
                            [in,out] LPSTR *ppszFileName);
        }    //==========================================================================
        [
    #ifdef UNICODE
            uuid(000214F9-0000-0000-C000-000000000046),
            helpstring("IShellLinkW Interface"),
    #else
            uuid(000214EE-0000-0000-C000-000000000046),
            helpstring("IShellLinkA Interface"),
    #endif
            odl, hidden
        ]    //==========================================================================
    #ifdef UNICODE
        interface IShellLinkW:IUnknown
    #else
        interface IShellLinkA:IUnknown
    #endif
        //==========================================================================
        {
            [helpstring("GetPath")]
            HRESULT GetPath(
                            [in]     ISTRING           pszFile,
                            [in]     long              cchMaxPath,
                            [in,out] WIN32_FIND_DATA  *pfd,
                            [in]     long              fflags);        [helpstring("GetIDList")]
            HRESULT GetIDList(
                            [in,out]  long  *ppidl);        [helpstring("SetIDList")]
            HRESULT SetIDList(
                            [in]      long   pidl);        [helpstring("GetDescription")]
            HRESULT GetDescription(
                            [in]      ISTRING  pszName,
                            [in]      long     cchMaxName);        [helpstring("SetDescription")]
            HRESULT SetDescription(
                            [in]      ISTRING  pszName);        [helpstring("GetWorkingDirectory")]
            HRESULT GetWorkingDirectory(
                            [in]      ISTRING  pszDir,
                            [in]      long     cchMaxPath);        [helpstring("SetWorkingDirectory")]
            HRESULT SetWorkingDirectory(
                            [in]      ISTRING  pszDir);        [helpstring("GetArguments")]
            HRESULT GetArguments(
                            [in]      ISTRING  pszArgs,
                            [in]      long     cchMaxPath);        [helpstring("SetArguments")]
            HRESULT SetArguments(
                            [in]      ISTRING  pszArgs);        [helpstring("GetHotkey")]
            HRESULT GetHotkey(
                            [in,out]  long    *pwHotkey);        [helpstring("SetHotkey")]
            HRESULT SetHotkey(
                            [in]      long    wHotkey);        [helpstring("GetShowCmd")]
            HRESULT GetShowCmd(
                            [in,out]  long   *piShowCmd);        [helpstring("SetShowCmd")]
            HRESULT SetShowCmd(
                            [in]      long    iShowCmd);        [helpstring("GetIconLocation")]
            HRESULT GetIconLocation(
                            [in]      ISTRING  pszIconPath,
                            [in]      long     cchIconPath,
                            [in,out]  long    *piIcon);        [helpstring("SetIconLocation")]
            HRESULT SetIconLocation(
                            [in]      ISTRING  pszIconPath,
                            [in]      long     iIcon);        [helpstring("SetRelativePath")]
            HRESULT SetRelativePath(
                            [in]      ISTRING  pszPathRel,
                            [in]      long     dwReserved);        [helpstring("Resolve")]
            HRESULT Resolve(
                            [in]      long     hwnd,
                            [in]      long     fflags);        [helpstring("SetPath")]
            HRESULT SetPath(
                            [in]      ISTRING  pszFile);
        }
    #ifdef UNICODE
        //==========================================================================
        [
            uuid(00021401-0000-0000-C000-000000000046),
            helpstring("ShellLinkW Class")
        ]
        //==========================================================================
        coclass ShellLinkW
        {
            [default] interface IShellLinkW;
        }
    #else
        //==========================================================================
        [
            uuid(00021401-0000-0000-C000-000000000046),
            helpstring("ShellLinkA Class")
        ]
        //==========================================================================
        coclass ShellLinkA
        {
            [default] interface IShellLinkA;
        }
    #endif
    }
    模块
    Attribute VB_Name = "mShellLink"
    Option Explicit'---------------------------------------------------------------
    '- Public API Declares...
    '---------------------------------------------------------------
    #If UNICODE Then
        Public Declare Function SHGetPathFromIDList Lib "Shell32" Alias "SHGetPathFromIDListW" (ByVal pidl As Long, ByVal szPath As Long) As Long
    #Else
        Public Declare Function SHGetPathFromIDList Lib "Shell32" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal szPath As String) As Long
    #End IfPublic Declare Function SHGetSpecialFolderLocation Lib "Shell32" (ByVal hwndOwner As Long, ByVal nFolder As Integer, ppidl As Long) As Long'---------------------------------------------------------------
    '- Public constants...
    '---------------------------------------------------------------
    Public Const MAX_PATH = 255
    Public Const MAX_NAME = 40类模块
    VERSION 1.0 CLASS
    BEGIN
      MultiUse = -1  'True
      Persistable = 0  'NotPersistable
      DataBindingBehavior = 0  'vbNone
      DataSourceBehavior  = 0  'vbNone
      MTSTransactionMode  = 0  'NotAnMTSObject
    END
    Attribute VB_Name = "cShellLink"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = True
    Attribute VB_PredeclaredId = False
    Attribute VB_Exposed = True
    Option Explicit'---------------------------------------------------------------
    '- Public enums...
    '---------------------------------------------------------------
    Public Enum STGM
        STGM_DIRECT = &H0&
        STGM_TRANSACTED = &H10000
        STGM_SIMPLE = &H8000000
        STGM_READ = &H0&
        STGM_WRITE = &H1&
        STGM_READWRITE = &H2&
        STGM_SHARE_DENY_NONE = &H40&
        STGM_SHARE_DENY_READ = &H30&
        STGM_SHARE_DENY_WRITE = &H20&
        STGM_SHARE_EXCLUSIVE = &H10&
        STGM_PRIORITY = &H40000
        STGM_DELETEONRELEASE = &H4000000
        STGM_CREATE = &H1000&
        STGM_CONVERT = &H20000
        STGM_FAILIFTHERE = &H0&
        STGM_NOSCRATCH = &H100000
    End EnumPublic Enum SHELLFOLDERS            ' Shell Folder Path Constants...
        CSIDL_DESKTOP = &H0&            ' ..\WinNT\profiles\username\Desktop
        CSIDL_PROGRAMS = &H2&           ' ..\WinNT\profiles\username\Start Menu\Programs
        CSIDL_CONTROLS = &H3&           ' No Path
        CSIDL_PRINTERS = &H4&           ' No Path
        CSIDL_PERSONAL = &H5&           ' ..\WinNT\profiles\username\Personal
        CSIDL_FAVORITES = &H6&          ' ..\WinNT\profiles\username\Favorites
        CSIDL_STARTUP = &H7&            ' ..\WinNT\profiles\username\Start Menu\Programs\Startup
        CSIDL_RECENT = &H8&             ' ..\WinNT\profiles\username\Recent
        CSIDL_SENDTO = &H9&             ' ..\WinNT\profiles\username\SendTo
        CSIDL_BITBUCKET = &HA&          ' No Path
        CSIDL_STARTMENU = &HB&          ' ..\WinNT\profiles\username\Start Menu
        CSIDL_DESKTOPDIRECTORY = &H10&  ' ..\WinNT\profiles\username\Desktop
        CSIDL_DRIVES = &H11&            ' No Path
        CSIDL_NETWORK = &H12&           ' No Path
        CSIDL_NETHOOD = &H13&           ' ..\WinNT\profiles\username\NetHood
        CSIDL_FONTS = &H14&             ' ..\WinNT\fonts
        CSIDL_TEMPLATES = &H15&         ' ..\WinNT\ShellNew
        CSIDL_COMMON_STARTMENU = &H16&  ' ..\WinNT\profiles\All Users\Start Menu
        CSIDL_COMMON_PROGRAMS = &H17&   ' ..\WinNT\profiles\All Users\Start Menu\Programs
        CSIDL_COMMON_STARTUP = &H18&    ' ..\WinNT\profiles\All Users\Start Menu\Programs\Startup
        CSIDL_COMMON_DESKTOPDIRECTORY = &H19& '..\WinNT\profiles\All Users\Desktop
        CSIDL_APPDATA = &H1A&           ' ..\WinNT\profiles\username\Application Data
        CSIDL_PRINTHOOD = &H1B&         ' ..\WinNT\profiles\username\PrintHood
    End EnumPublic Enum SHOWCMDFLAGS
        SHOWNORMAL = 5
        SHOWMAXIMIZE = 3
        SHOWMINIMIZE = 7
    End Enum'---------------------------------------------------------------
    Public Function GetSystemFolderPath(ByVal hwnd As Long, ByVal Id As Integer, sfPath As String) As Long
    '---------------------------------------------------------------
        Dim rc As Long                                      ' Return code
        Dim pidl As Long                                    ' ptr to Item ID List
        Dim cbPath As Long                                  ' char count of path
        Dim szPath As String                                ' String var for path
    '---------------------------------------------------------------
        szPath = Space(MAX_PATH)                            ' Pre-allocate path string for api call    rc = SHGetSpecialFolderLocation(hwnd, Id, pidl)     ' Get pidl for Id...
        If (rc = 0) Then                                    ' If success is 0
    #If UNICODE Then
            rc = SHGetPathFromIDList(pidl, StrPtr(szPath))  ' Get Path from Item Id List
    #Else
            rc = SHGetPathFromIDList(pidl, szPath)          ' Get Path from Item Id List
    #End If
            If (rc = 1) Then                                ' If success is 1
                szPath = Trim$(szPath)                      ' Fix path string
                cbPath = Len(szPath)                        ' Get length of path
                If (Asc(Right(szPath, 1)) = 0) Then cbPath = cbPath - 1 ' Adjust path length
                If (cbPath > 0) Then sfPath = Left$(szPath, cbPath) ' Adjust path string variable
                GetSystemFolderPath = True                  ' Return success
            End If
        End If
    '---------------------------------------------------------------
    End Function
    '---------------------------------------------------------------'---------------------------------------------------------------
    Public Function CreateShellLink(LnkFile As String, ExeFile As String, WorkDir As String, _
                                    ExeArgs As String, IconFile As String, IconIdx As Long, _
                                    ShowCmd As SHOWCMDFLAGS) As Long
    '---------------------------------------------------------------
        Dim rc As Long
        Dim pidl As Long                                    ' Item id list
        Dim dwReserved As Long                              ' Reserved flag
        Dim cShellLink As ShellLinkA                        ' An explorer IShellLinkA(Win 95/Win NT) instance
        Dim cPersistFile As IPersistFile                    ' An explorer IPersistFile instance
    '---------------------------------------------------------------
        If ((LnkFile = "") Or (ExeFile = "")) Then Exit Function    ' Validate min. input requirements.
        
        On Error GoTo ErrHandler
        Set cShellLink = New ShellLinkA                     ' Create new IShellLink interface
        Set cPersistFile = cShellLink                       ' Implement cShellLink's IPersistFile interface
        
        With cShellLink
            .SetPath ExeFile                                ' set command line exe name & path to new ShortCut.
            
            If (WorkDir <> "") Then .SetWorkingDirectory WorkDir ' Set working directory in shortcut
            
            If (ExeArgs <> "") Then .SetArguments ExeArgs   ' Add arguments to command line
            
    '       if (LnkDesc <> "") then .SetDescription pszName ' Set shortcut description
    '       .SetHotkey wHotKey
           
            If (IconFile <> "") Then .SetIconLocation IconFile, IconIdx ' Set shortcut icon location & index
            
            .SetDescription "ShellLink Sample" & vbNullChar
    '       .SetIDList pidl
    '       dwReserved = 0
    '       .SetRelativePath pszPathRel, dwReserved        .SetShowCmd ShowCmd                             ' Set shortcut's startup mode (min,max,normal)
        End With
        
        cShellLink.Resolve 0, SLR_UPDATE
        cPersistFile.Save StrConv(LnkFile, vbUnicode), 0     ' Unicode conversion hack... This must be done!
        CreateShellLink = True                              ' Return Success'---------------------------------------------------------------
    ErrHandler:
    '---------------------------------------------------------------
        Set cPersistFile = Nothing                          ' Destroy Object
        Set cShellLink = Nothing                            ' Destroy Object
    '---------------------------------------------------------------
    End Function
    '---------------------------------------------------------------'---------------------------------------------------------------
    Public Function GetShellLinkInfo(LnkFile As String, ExeFile As String, WorkDir As String, _
                                     ExeArgs As String, IconFile As String, IconIdx As Long, _
                                     ShowCmd As Long) As Long
    '---------------------------------------------------------------
        Dim pidl As Long                                    ' Item id list
        Dim wHotKey As Long                                 ' Hotkey to shortcut...
        Dim fd As WIN32_FIND_DATA
        Dim Description As String
        Dim buffLen As Long
        Dim cShellLink As ShellLinkA                        ' An explorer IShellLink instance
        Dim cPersistFile As IPersistFile                    ' An explorer IPersistFile instance
    '---------------------------------------------------------------
        If (LnkFile = "") Then Exit Function                ' Validate min. input requirements.
        
        Set cShellLink = New ShellLinkA                     ' Create new IShellLink interface
        Set cPersistFile = cShellLink                       ' Implement cShellLink's IPersistFile interface
        
        ' Load Shortcut file...(must do this UNICODE hack!)
        On Error GoTo ErrHandler
        cPersistFile.Load StrConv(LnkFile, vbUnicode), STGM_DIRECT
        
        With cShellLink
            ' Get command line exe name & path of shortcut
            ExeFile = Space(MAX_PATH)
            buffLen = Len(ExeFile)
            .GetPath ExeFile, buffLen, fd, SLGP_UNCPRIORITY
            Dim s As String
            s = fd.cFileName                                ' Not returned to calling function
            
            ' Get working directory of shortcut
            WorkDir = Space(MAX_PATH)
            buffLen = Len(WorkDir)
            .GetWorkingDirectory WorkDir, buffLen
            
            ' Get command line arguments of shortcut
            ExeArgs = Space(MAX_PATH)
            buffLen = Len(ExeArgs)
            .GetArguments ExeArgs, buffLen
            
            ' Get description of shortcut
            Description = Space(MAX_PATH)
            buffLen = Len(Description)
            .GetDescription Description, buffLen            ' Not returned to calling function
            
            ' Get the HotKey for shortcut
            .GetHotkey wHotKey                              ' Not returned to calling function
           
            ' Get shortcut icon location & index
            IconFile = Space(MAX_PATH)
            buffLen = Len(IconFile)
            .GetIconLocation IconFile, buffLen, IconIdx
            
            ' Get Item ID List...
            .GetIDList pidl                                 ' Not returned to calling function
                    
            ' Set shortcut's startup mode (min,max,normal)
            .GetShowCmd ShowCmd
        End With    GetShellLinkInfo = True                             ' Return Success
    '---------------------------------------------------------------
    ErrHandler:
    '---------------------------------------------------------------
        Set cPersistFile = Nothing                          ' Destroy Object
        Set cShellLink = Nothing                            ' Destroy Object
    '---------------------------------------------------------------
    End Function
    '---------------------------------------------------------------
    '在工程中引用Shelllnk.tlb即可
    'CreateShellLink  创建一个快捷方式
    'GetShellLinkInfo 得到快捷方式的信息
      

  5.   

    用文本打开.lnk文件可以看到目标路径
    我想总结一下规律就可以了搞定了
      

  6.   

    关于"快捷方式"的几个问题 (引用 Windows Script Host Model) ....
    http://www.csdn.net/expert/TopicView.asp?id=214456我的这张帖子,至今无人问津,今天终于被派上用场了!