1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
#define WIN32_LEAN_AND_MEAN
#define WINVER 0x0602
#define _WIN32_WINNT 0x0602
#define _WIN32_IE 0x0602
#include <windows.h>
#include <objbase.h>
#include <shlobj.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#ifdef _UNICODE
#define TCOUT std::wcout
#define TCERR std::wcerr
#else
#define TCOUT std::cout
#define TCERR std::cerr
#endif
HRESULT ResolveIt(HWND hwnd, LPCTSTR lpszLinkFile, LPTSTR lpszPath, int iPathBufferSize);
int main()
{
const TCHAR cachLinkFile[] = TEXT("D:\\dev\\projects.lnk");
HRESULT hres = CoInitialize(NULL);
if(SUCCEEDED(hres))
{
TCHAR achPath[MAX_PATH] = {0};
hres = ResolveIt(NULL, cachLinkFile, achPath, MAX_PATH);
if (SUCCEEDED(hres))
{
TCOUT << TEXT("Succeeded: path = ") << achPath << std::endl;
}
else
{
TCERR << TEXT("Failed: error = 0x") << std::hex << hres << std::dec << std::endl;
}
CoUninitialize();
}
return 0;
}
HRESULT ResolveIt(HWND hwnd, LPCTSTR lpszLinkFile, LPTSTR lpszPath, int iPathBufferSize)
{
if (lpszPath == NULL)
return E_INVALIDARG;
*lpszPath = 0;
// Get a pointer to the IShellLink interface. It is assumed that CoInitialize
// has already been called.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
if (SUCCEEDED(hres))
{
// Get a pointer to the IPersistFile interface.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile, (void**)&ppf);
if (SUCCEEDED(hres))
{
// Add code here to check return value from MultiByteWideChar
// for success.
// Load the shortcut.
#ifdef _UNICODE
hres = ppf->Load(lpszLinkFile, STGM_READ);
#else
WCHAR wsz[MAX_PATH] = {0};
// Ensure that the string is Unicode.
MultiByteToWideChar(CP_ACP, 0, lpszLinkFile, -1, wsz, MAX_PATH);
hres = ppf->Load(wsz, STGM_READ);
#endif
if (SUCCEEDED(hres))
{
// Resolve the link.
hres = psl->Resolve(hwnd, 0);
if (SUCCEEDED(hres))
{
// Get the path to the link target.
TCHAR szGotPath[MAX_PATH] = {0};
hres = psl->GetPath(szGotPath, MAX_PATH, NULL, SLGP_SHORTPATH);
if (SUCCEEDED(hres))
{
memcpy(lpszPath,szGotPath,iPathBufferSize);
}
}
}
// Release the pointer to the IPersistFile interface.
ppf->Release();
}
// Release the pointer to the IShellLink interface.
psl->Release();
}
return hres;
}
|