c++qtwinapimingw

IPersistFile Load undefined return value


I'm currently trying to port the example Resolving a Shortcut on MSDN to a QT application built with MinGW 4.8.1.

My code (stripped of error checks for shortness) currently looks like this:

QFileInfo shortcut("C:\\Users\\MyUserName\\ShortCut.lnk");

HRESULT apiResult;
IShellLink *shellLink;

apiResult = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                             IID_IShellLink, (LPVOID*) &shellLink);

IPersistFile *persistFile;
apiResult = shellLink->QueryInterface(IID_IPersistFile, (void**) &persistFile);

WCHAR shortcutLocationWchar[MAX_PATH];
QString shortcutLocation = QDir::toNativeSeparators(shortcut.absoluteFilePath());
shortcutLocation.toWCharArray(shortcutLocationWchar);

apiResult = persistFile->Load(shortcutLocationWchar, STGM_READ);

apiResult = shellLink->Resolve(NULL, SLR_NO_UI);

WCHAR shortcutTargetWchar[MAX_PATH];
WIN32_FIND_DATA winFindData;
apiResult = shellLink->GetPath(shortcutTargetWchar, MAX_PATH, &winFindData, 0);

QString shortcutTarget = QString::fromWCharArray(shortcutTargetWchar);

At the moment IPersistFile::Load fails with return value 0x80070002, what is neither defined in its API Document, nor the winerr.h header nor Google seems to come up with any useful results.

Any suggestions what is going wrong here?


Solution

  • I missed an important line in the API documentation for QString::toWcharArrar():

    Note: This function does not append a null character to the array.

    So the correct way would convert the shortcut file name to WCHAR array is

    WCHAR shortcutLocationWchar[MAX_PATH];
    QString shortcutLocation = QDir::toNativeSeparators(shortcut.absoluteFilePath());
    int l = shortcutLocation.toWCharArray(shortcutLocationWchar);
    shortcutLocationWchar[l] = L'\0';