2012年7月5日星期四

Shortcut.Cpp


#include "windows.h"
//#include "winnls.h"
#include "shobjidl.h"
//#include "objbase.h"
//#include "objidl.h"
#include "shlguid.h"

HRESULT CreateLink(LPCWSTR lpszPathObj, LPCSTR lpszPathLink, LPCWSTR lpszDesc) 
    CoInitialize(0);//有一个参数

    IShellLink * psl; 
    HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl); 
    if (SUCCEEDED(hres)) 
    {           
        psl->SetPath(lpszPathObj); // Set the path to the shortcut target and add the description. 
        psl->SetDescription(lpszDesc); 

        IPersistFile * ppf; 
        hres = psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf); 
        if (SUCCEEDED(hres)) 
        { 
            WCHAR wsz[MAX_PATH]; 
            MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1, wsz, MAX_PATH);              
            hres = ppf->Save(wsz, TRUE); // Save the link by calling IPersistFile::Save.
            ppf->Release(); 
        } 
        psl->Release(); 
    } 

    CoUninitialize();//无参数
    return hres; 
}

int _tmain(int argc, _TCHAR* argv[])
{    
    wchar_t lpszPathObj[MAX_PATH] = L"C:\\Windows\\regedit.exe";//可以为文件也可以为文件夹
    char lnk[MAX_PATH] = "c:\\regedit.lnk";//这里的后缀名必须是.lnk,无后缀名或者改为url等其他的都不行。
    CreateLink(lpszPathObj, lnk, L"made by correy") ;   
    return 0;
}
//本文修改自msdn。 

没有评论:

发表评论