在 WinForms 應用程式中,將指定 URL 儲存為「我的最愛」快捷方式(.url 檔案),支援自訂名稱與子資料夾。
Environment.GetFolderPath(Environment.SpecialFolder.Favorites)。IWshRuntimeLibrary)建立網際網路捷徑。using System;
using System.IO;
using IWshRuntimeLibrary; // 參考 COM: "Windows Script Host Object Model"
public class FavoritesHelper
{
public static void AddToFavorites(string url, string name, string subFolder = "")
{
string favRoot = Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
string targetDir = string.IsNullOrEmpty(subFolder) ? favRoot : Path.Combine(favRoot, subFolder);
string shortcutPath = Path.Combine(targetDir, $"{name}.url");
if (File.Exists(shortcutPath)) return; // 已存在則略過
Directory.CreateDirectory(targetDir); // 確保子資料夾存在
var shell = new IWshShell_Class();
IWshURLShortcut shortcut = (IWshURLShortcut)shell.CreateShortcut(shortcutPath);
shortcut.TargetPath = url;
shortcut.Save();
}
}
// 直接加入我的最愛根目錄
FavoritesHelper.AddToFavorites("https://learn.microsoft.com", "MS Learn");
// 加入子資料夾 "開發工具"
FavoritesHelper.AddToFavorites("https://github.com", "GitHub", "開發工具");
IWshURLShortcut 專門用於建立網址捷徑,TargetPath 接受完整 URL。shortcut.IconLocation(需 .ico 檔案路徑)。原文提到的副問題:AxWebBrowser(舊版 WebBrowser ActiveX)無直接 StatusText 屬性。解法:
// 需參考 SHDocVw (Microsoft Internet Controls)
SHDocVw.WebBrowser wb = axWebBrowser.GetOcx() as SHDocVw.WebBrowser;
string status = wb.StatusText; // 或處理 StatusTextChange 事件
現代專案建議改用 WebView2 (Edge Chromium) 取代舊版 WebBrowser。