首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# WinForms 將網頁加入我的最愛(收藏夾)完整實作

     編輯:關於C語言

需求

在 WinForms 應用程式中,將指定 URL 儲存為「我的最愛」快捷方式(.url 檔案),支援自訂名稱與子資料夾。

核心步驟

  1. 取得目前使用者「我的最愛」資料夾路徑:Environment.GetFolderPath(Environment.SpecialFolder.Favorites)。
  2. 使用 COM 元件 Windows Script Host Object Model(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", "開發工具");

關鍵細節

  • 參考加入方式:專案 → 加入參考 → COM 標籤 → 勾選 "Windows Script Host Object Model"。
  • IWshURLShortcut 專門用於建立網址捷徑,TargetPath 接受完整 URL。
  • 若需支援圖示,可設定 shortcut.IconLocation(需 .ico 檔案路徑)。
  • 權限:寫入「我的最愛」通常不需管理員權限,但受限於使用者帳號控制 (UAC) 原則。

常見問題:AxWebBrowser 取得 StatusText

原文提到的副問題: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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved