C++:如何在 Windows 的开始菜单中创建快捷方式 [英] C++: How do I create a Shortcut in the Start Menu on Windows

查看:43
本文介绍了C++:如何在 Windows 的开始菜单中创建快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to know how to obtain the path to the start menu folder on Windows and then create a shortcut to a path that might contain non-ASCII characters.

推荐答案

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

Here is the solution. It uses Qt but it's also possible without. Then just use std::wstring instead of QString. For concatenating the paths and filenames you will then have to use string operations instead of using 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;
}

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

Thats the part that obtains the location of the start-menu folder:

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

剩下的就是创建快捷方式了.为您想要的值交换快捷方式名称和描述.

The rest is then creation of the shortcut. Exchange shortcut name and description for your desired values.

这篇关于C++:如何在 Windows 的开始菜单中创建快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆