本文介绍如何在WIN32下使用VC++为一个应用程序创建快捷方式!
首先包含头文件:
#include <Windows.h>
#include <ShObjIdl.h>
#include <ShlGuid.h>
创建快捷方式的函数:CreateLink
lpszPathObj为要创建快捷方式的exe路径
lpszPathLink为快捷方式的路径
lpszDesc为快捷方式的描述NULL为没有
lpszArgs为启动方式的启动参数 NULL表示没有启动参数
lpszIcon为使用的图标 NULL 则使用exe的图标
HRESULT CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszPathLink, LPCWSTR lpszDesc = NULL, LPCWSTR lpszArgs = NULL, LPCWSTR lpszIcon = NULL)
{
HRESULT hres;
IShellLink* psl;
// Get a pointer to the IShellLink interface. It is assumed that CoInitialize
// has already been called.
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
DWORD errorCode = ::GetLastError();
if (SUCCEEDED(hres))
{
IPersistFile* ppf;
// Set the path to the shortcut target and add the description.
psl->SetPath(lpszPathObj);
if(lpszDesc)
{
psl->SetDescription(lpszDesc);
}
if(lpszIcon)
{
psl->SetIconLocation(lpszIcon, 0);
}
if(lpszArgs)
{
psl->SetArguments(lpszArgs);
}
// Query IShellLink for the IPersistFile interface, used for saving the
// shortcut in persistent storage.
hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);
if (SUCCEEDED(hres))
{
/*
WCHAR wsz[MAX_PATH];
// Ensure that the string is Unicode.
MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1, wsz, MAX_PATH);
*/
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(lpszPathLink, TRUE);
ppf->Release();
}
psl->Release();
}
return hres;
}
使用方式:
<注意要初始化Com组件,CoInitialize>
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(0);
CreateLink(L"G:\\测试\\Client.exe",L"C:\\Users\\me\\Desktop\\CreateLink.lnk",L"Customer Desc", L"-noupdate", L"G:\\测试\\Client.ico");
CoUninitialize();
return 0;
}
即可在桌面为G:\\测试\\Client.exe创建一个快捷方式(图标为Client.ico, 启动参数为noupdate。)