C++:如何在 Windows 的“开始”菜单中创建快捷方式

2023-12-29

我想知道如何获取 Windows 上开始菜单文件夹的路径,然后创建可能包含非 ASCII 字符的路径的快捷方式。


这是解决方案。它使用 Qt,但也可以不使用。然后只需使用std::wstring代替QString。为了连接路径和文件名,您将不得不使用字符串操作而不是使用QDir.

#include <shlobj.h> 

bool createStartMenuEntry(QString targetPath) {
    targetPath = QDir::toNativeSeparators(targetPath);

    WCHAR startMenuPath[MAX_PATH];
    HRESULT result = SHGetFolderPathW(NULL, CSIDL_COMMON_PROGRAMS, NULL, 0, startMenuPath);

    if (SUCCEEDED(result)) {
        QString linkPath = QDir(QString::fromWCharArray(startMenuPath)).absoluteFilePath("Shortcut Name.lnk");

        CoInitialize(NULL);
        IShellLinkW* shellLink = NULL;
        result = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_ALL, IID_IShellLinkW, (void**)&shellLink);
        if (SUCCEEDED(result)) {
            shellLink->SetPath(targetPath.toStdWString().c_str());
            shellLink->SetDescription(L"Shortcut Description");
            shellLink->SetIconLocation(targetPath.toStdWString().c_str(), 0);
            IPersistFile* persistFile;
            result = shellLink->QueryInterface(IID_IPersistFile, (void**)&persistFile);

            if (SUCCEEDED(result)) {
                result = persistFile->Save(linkPath.toStdWString().c_str(), TRUE);

                persistFile->Release();
            } else {
                return false;
            }
            shellLink->Release();
        } else {
            return false;
        }
    } else {
        return false;
    }
    return true;
}

这就是获取开始菜单文件夹位置的部分:

WCHAR startMenuPath[MAX_PATH];
HRESULT result = SHGetFolderPathW(NULL, CSIDL_COMMON_PROGRAMS, NULL, 0, startMenuPath);

剩下的就是创建快捷方式。将快捷方式名称和描述替换为您想要的值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++:如何在 Windows 的“开始”菜单中创建快捷方式 的相关文章

随机推荐