如何在桌面或者开始菜单中创建快捷方式

来源:互联网 发布:西安旅游 知乎 编辑:程序博客网 时间:2024/05/21 11:12

源地址:http://blog.csdn.net/vcforever/article/details/326269

作者:vcforever

//在桌面或者开始菜单中创建快捷方式//pazSrcPath:源文件路径//bDesktop:标志位,用来判断是否在桌面上创建快捷方式,真,在桌面上创建,否则在开始菜单中创建bool createShortcut(const char* pszSrcPath, bool bDesktop){    CoInitialize(NULL);    bool bRet = false;    IShellLink* psl;    LPITEMIDLIST pidl;    LPMALLOC pShellMalloc;    std::string strDesktopPath;    std::string strStartMenuPath;    const int nFolder[2] = { CSIDL_DESKTOPDIRECTORY,CSIDL_STARTMENU };    if (SUCCEEDED(SHGetMalloc(&pShellMalloc))) {        char Path[MAX_PATH + 1];        for (int i = 0; i < 2; i++) {            if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, nFolder[i], &pidl))) {                if (SHGetPathFromIDList(pidl, Path)) {                    if (i == 0)                        strDesktopPath = Path;                    else                        strStartMenuPath = Path;                }                pShellMalloc->Free(pidl);            }        }        pShellMalloc->Release();    }    char szFileTitle[MAX_PATH] = { 0 };    ::GetFileTitle(pszSrcPath, szFileTitle, MAX_PATH);    std::string str;    if (bDesktop)        str = strDesktopPath;    else        str = strStartMenuPath;    str += "//";    str += std::string(szFileTitle);    str += ".lnk";    HRESULT hr = CoCreateInstance(CLSID_ShellLink,             NULL,CLSCTX_INPROC_SERVER,             IID_IShellLink,             (LPVOID*)&psl);    if (SUCCEEDED(hr)) {        IPersistFile* ppf;        psl->SetPath(pszSrcPath);        psl->SetDescription("Shortcut created by custom code");        psl->SetShowCmd(SW_SHOW);        if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf))) {            WORD mbw[MAX_PATH];            MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, str.c_str(), -1, mbw, MAX_PATH);            if (SUCCEEDED(ppf->Save(mbw, TRUE)))                bRet = true;            ppf->Release();        }        psl->Release();    }    CoUninitialize();    return bRet;}