我试图显示快捷方式(.lnk)文件的真实路径(目标)。所以我在项目的corrent文件夹中复制并粘贴(test.lnk),我试图显示其目标
#include <windows.h>
#include <string>
#include <iostream>
#include <objidl.h> /* For IPersistFile */
#include <shlobj.h> /* For IShellLink */
#include "objbase.h"
using namespace std;
/*********************************************************************
* Function......: ResolveShortcut
* Parameters....: lpszShortcutPath - string that specifies a path
and file name of a shortcut
* lpszFilePath - string that will contain a file name
* Returns.......: S_OK on success, error code on failure
* Description...: Resolves a Shell link object (shortcut)
*********************************************************************/
HRESULT ResolveShortcut(/*in*/ LPCTSTR lpszShortcutPath,
/*out*/ LPTSTR lpszFilePath)
{
HRESULT hRes = E_FAIL;
IShellLink* psl = NULL;
// buffer that receives the null-terminated string
// for the drive and path
TCHAR szPath[MAX_PATH];
// buffer that receives the null-terminated
// string for the description
TCHAR szDesc[MAX_PATH];
// structure that receives the information about the shortcut
WIN32_FIND_DATA wfd;
WCHAR wszTemp[MAX_PATH];
lpszFilePath[0] = '\0';
// Get a pointer to the IShellLink interface
hRes = CoCreateInstance(CLSID_ShellLink,
NULL,
CLSCTX_INPROC_SERVER,
IID_IShellLink,
(void**)&psl);
if (SUCCEEDED(hRes))
{
// Get a pointer to the IPersistFile interface
IPersistFile* ppf = NULL;
psl->QueryInterface(IID_IPersistFile, (void **) &ppf);
// IPersistFile is using LPCOLESTR,
// so make sure that the string is Unicode
#if !defined _UNICODE
MultiByteToWideChar(CP_ACP, 0, lpszShortcutPath,
-1, wszTemp, MAX_PATH);
#else
wcsncpy(wszTemp, lpszShortcutPath, MAX_PATH);
#endif
// Open the shortcut file and initialize it from its contents
hRes = ppf->Load(wszTemp, STGM_READ);
if (SUCCEEDED(hRes))
{
// Try to find the target of a shortcut,
// even if it has been moved or renamed
hRes = psl->Resolve(NULL, SLR_UPDATE);
if (SUCCEEDED(hRes))
{
// Get the path to the shortcut target
hRes = psl->GetPath(szPath,
MAX_PATH, &wfd, SLGP_RAWPATH);
if (FAILED(hRes))
return hRes;
// Get the description of the target
hRes = psl->GetDescription(szDesc,
MAX_PATH);
if (FAILED(hRes))
return hRes;
lstrcpyn(lpszFilePath, szPath, MAX_PATH);
}
}
}
return hRes;
}
int main(void)
{
LPCTSTR lpszShortcutPath =("test.lnk");
TCHAR szFilePath[MAX_PATH];
HRESULT hRes =ResolveShortcut(lpszShortcutPath, szFilePath);
cout << TEXT("Succeeded: path = ") <<hRes ;
return 0;
}
显示Succeeded:path = -2134343
有人可以帮我显示.lnk文件的真实目标及其描述。
答案 0 :(得分:1)
您可能忘了拨打CoInitialize
启动主要功能:
int main(void)
{
CoInitialize(NULL); //<< add
LPCTSTR lpszShortcutPath....
CoUninitialize(); //<< add
}