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

C# 純程式碼建立桌面捷徑、開始功能表項目與我的最愛網頁捷徑

     編輯:關於C#

功能展示

  • 建立桌面捷徑
  • 建立開始功能表項目(可指定子資料夾)
  • 將網頁加入我的最愛

核心 COM 介面封裝

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 取得特殊資料夾路徑。

原始碼下載

建立捷徑完整原始碼

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