1 BOOL CFileTool::CreateShortcuts(const CString *pFile,
2 const CString *pPath,
3 const CString *pIconLocation,
4 const CString *pArguments,
5 const CString *pWorkingDirectory,
6 WORD pHotkey,
7 int pShowCmd,
8 const PCIDLIST_ABSOLUTE pIDList,
9 const CString *pRelativePat,
10 const CString *pDescription)
11 {
12 // 入口参数检查
13 if (NULL == pFile || NULL == pPath)
14 {
15 return FALSE;
16 }
17
18 HRESULT hRet;
19 //初始化COM库
20 hRet = ::CoInitialize(NULL);
21 if (hRet != S_OK) //初始化COM库失败,直接返回
22 {
23 return FALSE;
24 }
25
26 IShellLink *psl = NULL; //IShellLink对象指针
27 IPersistFile *ppf = NULL; //IPersisFil对象指针
28
29 //创建IShellLink实例
30 hRet = ::CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
31 IID_IShellLink, (void**)&psl);
32 if (hRet != S_OK) //初始化COM库失败,直接返回
33 {
34 //释放COM接口
35 ::CoUninitialize();
36 return FALSE;
37 }
38
39 //从IShellLink对象中获取IPersistFile接口
40 hRet = psl->QueryInterface(IID_IPersistFile, (void**)&ppf);
41 if (hRet != S_OK) //初始化COM库失败,直接返回
42 {
43 //释放IShellLink对象
44 psl->Release();
45 //释放COM接口
46 ::CoUninitialize();
47 return FALSE;
48 }
49
50 //1.设置快捷方式中的程序路径
51 psl->SetPath(*pPath);
52
53 //2.设置图标
54 if (pIconLocation != NULL && pIconLocation[0] != L'\0')
55 {
56 psl->SetIconLocation(*pIconLocation, 0);
57 }
58
59 //3.设置快捷方式的工作目录
60 if (pWorkingDirectory != NULL && pWorkingDirectory[0] != L'\0')
61 {
62 psl->SetWorkingDirectory(*pWorkingDirectory);
63 }
64
65 //4.快捷键
66 if (pHotkey > 0)
67 {
68 psl->SetHotkey(pHotkey);
69 }
70
71 //5.快捷方式的运行方式,比如常规窗口,最大化
72 if (pShowCmd >= 0)
73 {
74 psl->SetShowCmd(pShowCmd);
75 }
76
77 //6.获得快捷方式的目标对象的item identifier list (Windows外壳中的每个对象如文件,目录和打印机等都有唯一的item identifiler list)
78 if (pIDList != NULL)
79 {
80 psl->SetIDList(pIDList);
81 }
82
83 //7.按照一定的搜索规则试图获得目标对象,即使目标对象已经被删除或移动,重命名
84 if (pRelativePat != NULL && pRelativePat[0] != L'\0')
85 {
86 psl->SetRelativePath(*pRelativePat, 0);
87 }
88
89 //8.参数信息
90 if (pArguments != NULL && pArguments[0] != L'\0')
91 {
92 psl->SetArguments(*pArguments);
93 }
94
95 //9.描述信息(备注行)
96 if (pDescription != NULL && pDescription[0] != L'\0')
97 {
98 psl->SetDescription(*pDescription);
99 }
100
101 //确保快捷方式路径由ANSI字符串组成
102 //!!这个文件名改变了,就需要删除原有快捷方式,没改,就直接创建,不用删除原有的。
103 //CString wsz = L"C:\\Documents and Settings\\Gongjian\\桌面\\vc创建的快捷方式.lnk";
104
105 //保存快捷方式
106 ppf->Save(*pFile, TRUE);
107
108
109 //释放IPersistFile接口
110 ppf->Release();
111 //释放IShellLink对象
112 psl->Release();
113 //释放COM接口
114 ::CoUninitialize();
115
116 return TRUE;
117 }