您的位置:首页 > 其它

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

2005-03-22 10:06 701 查看
//在桌面或者开始菜单中创建快捷方式
//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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  path string null server