Skip to content

Instantly share code, notes, and snippets.

@katahiromz
Created August 15, 2019 09:39
Show Gist options
  • Save katahiromz/4b3f4870581d6350d92afe1a355ff2ab to your computer and use it in GitHub Desktop.
Save katahiromz/4b3f4870581d6350d92afe1a355ff2ab to your computer and use it in GitHub Desktop.
GetPathOfShortcut
#include <windows.h>
#include <shlobj.h>
BOOL GetPathOfShortcut(HWND hWnd, LPCTSTR pszLnkFile, LPTSTR pszPath)
{
TCHAR szPath[MAX_PATH];
#ifndef UNICODE
WCHAR wsz[MAX_PATH];
#endif
IShellLink* pShellLink;
IPersistFile* pPersistFile;
WIN32_FIND_DATA find;
BOOL bRes = FALSE;
szPath[0] = '\0';
HRESULT hRes = CoInitialize(NULL);
if (SUCCEEDED(hRes))
{
if (SUCCEEDED(hRes = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&pShellLink)))
{
if (SUCCEEDED(hRes = pShellLink->QueryInterface(IID_IPersistFile,
(VOID **)&pPersistFile)))
{
#ifndef UNICODE
MultiByteToWideChar(CP_ACP, 0, pszLnkFile, -1, wsz, MAX_PATH);
hRes = pPersistFile->Load(wsz, STGM_READ);
#else
hRes = pPersistFile->Load(pszLnkFile, STGM_READ);
#endif
if (SUCCEEDED(hRes))
{
if (SUCCEEDED(hRes = pShellLink->GetPath(szPath,
MAX_PATH, &find, SLGP_SHORTPATH)))
{
if ('\0' != szPath[0])
{
lstrcpy(pszPath, szPath);
bRes = TRUE;
}
}
}
pPersistFile->Release();
}
pShellLink->Release();
}
CoUninitialize();
}
return bRes;
}
#ifdef UNITTEST
#include <stdio.h>
int main(int argc, char **argv)
{
BOOL f;
TCHAR szPath[MAX_PATH];
f = GetPathOfShortcut(NULL, argv[1], szPath);
printf("Path: %s\n", szPath);
return f;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment