public const int SW_SHOWNORMAL = 1;
public static bool CreateShortcut(string shortcutPath, string targetPath, string workingDirectory, string description, string iconLocation = null) {
try {
CShellLink cShellLink = new CShellLink();
IShellLink iShellLink = (IShellLink)cShellLink;
iShellLink.SetDescription(description);
iShellLink.SetShowCmd(SW_SHOWNORMAL);
iShellLink.SetPath(targetPath);
iShellLink.SetWorkingDirectory(workingDirectory);
if (!string.IsNullOrEmpty(iconLocation))
iShellLink.SetIconLocation(iconLocation, 0);
IPersistFile iPersistFile = (IPersistFile)iShellLink;
iPersistFile.Save(shortcutPath, false);
// 釋放 COM 物件
Marshal.ReleaseComObject(iPersistFile);
Marshal.ReleaseComObject(iShellLink);
Marshal.ReleaseComObject(cShellLink);
return true;
}
catch { return false; }
}
// 桌面捷徑
public static bool CreateDesktopShortcut(string targetPath, string description, string iconLocation = null, string workingDirectory = null) {
if (string.IsNullOrEmpty(workingDirectory)) workingDirectory = GetDeskDir();
return CreateShortcut(GetDeskDir() + "\\" + description + ".lnk", targetPath, workingDirectory, description, iconLocation);
}
// 開始功能表捷徑
public static bool CreateProgramsShortcut(string targetPath, string description, string menuName, string iconLocation = null, string workingDirectory = null) {
if (string.IsNullOrEmpty(workingDirectory)) workingDirectory = GetProgramsDir();
string shortcutPath = GetProgramsDir();
if (!string.IsNullOrEmpty(menuName)) {
shortcutPath += "\\" + menuName;
if (!Directory.Exists(shortcutPath)) Directory.CreateDirectory(shortcutPath);
}
shortcutPath += "\\" + description + ".lnk";
return CreateShortcut(shortcutPath, targetPath, workingDirectory, description, iconLocation);
}
// 我的最愛網頁捷徑
public static bool AddFavorites(string url, string description, string folderName, string iconLocation = null, string workingDirectory = null) {
if (string.IsNullOrEmpty(workingDirectory)) workingDirectory = GetProgramsDir();
string shortcutPath = GetFavoriteDir();
if (!string.IsNullOrEmpty(folderName)) {
shortcutPath += "\\" + folderName;
if (!Directory.Exists(shortcutPath)) Directory.CreateDirectory(shortcutPath);
}
shortcutPath += "\\" + description + ".lnk";
return CreateShortcut(shortcutPath, url, workingDirectory, description, iconLocation);
}
輔助方法 GetDeskDir、GetProgramsDir、GetFavoriteDir 需透過 SHGetFolderPath 或 Environment.GetFolderPath 取得特殊資料夾路徑。