#define NO_WIN32_LEAN_AND_MEAN
#include
#include
struct TShortcutCfg {
TShortcutCfg() {
nShowCmd = SW_SHOWNORMAL;
wHotKey = 0;
nIconIndex = 0;
}
AnsiString strShortcutName; // 捷徑名稱
AnsiString strLnkDir; // 捷徑目錄 (快速啟動列路徑)
AnsiString strDestFile; // 目標執行檔路徑
AnsiString strArguments; // 命令列參數
AnsiString strIconFile; // 圖示檔案路徑
int nIconIndex; // 圖示索引
AnsiString strWorkingDir; // 工作目錄
AnsiString strDescription; // 工具提示描述
WORD wHotKey; // 熱鍵
int nShowCmd; // 視窗顯示狀態
};
bool CreateQuickLaunchShortcut(TShortcutCfg *scConfig) {
char szBuf[MAX_PATH];
bool bReturn = true;
wchar_t wszBuf[MAX_PATH];
IShellLink *pShellLink;
AnsiString strShortcutFile;
LPITEMIDLIST lpItemIdList;
// 1. 取得 Application Data 目錄 (CSIDL_APPDATA)
SHGetSpecialFolderLocation(0, CSIDL_APPDATA, &lpItemIdList);
SHGetPathFromIDList(lpItemIdList, szBuf);
if (DirectoryExists(AnsiString(szBuf))) {
// 快速啟動列路徑: %APPDATA%\Microsoft\Internet Explorer\Quick Launch\
strShortcutFile = AnsiString(szBuf)
+ "\\Microsoft\\Internet Explorer\\Quick Launch\\"
+ scConfig->strShortcutName + ".lnk";
strShortcutFile.WideChar(wszBuf, MAX_PATH);
} else {
bReturn = false;
}
// 2. 建立 ShellLink COM 物件
if (bReturn) {
bReturn = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
IID_IShellLink, (void**)&pShellLink) >= 0;
}
// 3. 取得 IPersistFile 介面以儲存捷徑檔
if (bReturn) {
IPersistFile *ppf;
bReturn = pShellLink->QueryInterface(IID_IPersistFile, (void**)&ppf) >= 0;
if (bReturn) {
// 設定目標檔案
if (scConfig->strDestFile != EmptyStr)
bReturn = pShellLink->SetPath(scConfig->strDestFile.c_str()) >= 0;
// 設定參數
if (bReturn && scConfig->strArguments != EmptyStr)
bReturn = pShellLink->SetArguments(scConfig->strArguments.c_str()) >= 0;
// 設定圖示
if (bReturn && scConfig->strIconFile != EmptyStr && FileExists(scConfig->strIconFile))
pShellLink->SetIconLocation(scConfig->strIconFile.c_str(), scConfig->nIconIndex);
// 設定工作目錄
if (bReturn && scConfig->strWorkingDir != EmptyStr)
pShellLink->SetWorkingDirectory(scConfig->strWorkingDir.c_str());
// 設定描述 (工具提示)
if (bReturn && scConfig->strDescription != EmptyStr)
pShellLink->SetDescription(scConfig->strDescription.c_str());
// 設定熱鍵
if (bReturn && scConfig->wHotKey != 0)
pShellLink->SetHotkey(scConfig->wHotKey);
// 設定視窗顯示狀態
if (bReturn && scConfig->nShowCmd != 0)
pShellLink->SetShowCmd(scConfig->nShowCmd);
// 儲存捷徑檔
if (bReturn)
bReturn = (ppf->Save(wszBuf, TRUE) >= 0);
ppf->Release();
}
pShellLink->Release();
}
return bReturn;
}
void __fastcall TForm1::Button1Click(TObject *Sender) {
TShortcutCfg scShortcut;
scShortcut.strDestFile = "C:\\123\\123.exe";
scShortcut.strShortcutName = "test";
if (CreateQuickLaunchShortcut(&scShortcut))
ShowMessage("在快速啟動欄建立捷徑成功!");
}
Save() 方法需 Unicode 路徑同樣原理可用於建立桌面捷徑、開始選單捷徑,只需修改 SHGetSpecialFolderLocation 的 CSIDL 參數 (如 CSIDL_DESKTOPDIRECTORY、CSIDL_STARTMENU)。