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

C# 創建與應用快捷方式完整指南

     編輯:關於C語言

概述

通過 WshShell COM 組件,C# 可輕鬆創建 Windows 快捷方式(.lnk),並設置目標路徑、工作目錄、窗口狀態、圖標、熱鍵等屬性。本文系統梳理核心屬性與實戰技巧。

核心步驟

  1. 創建 WshShell 實例;
  2. 調用 CreateShortcut(string path) 獲取 IWshShortcut;
  3. 設置屬性;
  4. 調用 Save() 持久化。

關鍵屬性詳解

屬性用途示例
TargetPath目標程序/文件完整路徑shortcut.TargetPath = Application.ExecutablePath;
WorkingDirectory啟動時的工作目錄shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
WindowStyle窗口顯示狀態:1=正常, 3=最大化, 7=最小化shortcut.WindowStyle = 3;
Description懸停提示/備註shortcut.Description = "啟動我的應用";
IconLocation圖標路徑與索引,格式 path,indexshortcut.IconLocation = @"%SystemRoot%\System32\Shell32.dll, 165";
Arguments傳遞給目標程序的命令行參數shortcut.Arguments = "/out:output.txt /sortby:date /desc";
Hotkey全局熱鍵(無空格),如 CTRL+ALT+F11shortcut.Hotkey = "CTRL+ALT+F11";

完整代碼示例

using System;
using IWshRuntimeLibrary; // 需引用 COM "Windows Script Host Object Model"

public class ShortcutHelper
{
    public static void CreateShortcut(string linkPath, string targetPath, string args = "", string hotkey = "", string description = "", string iconPath = "", int iconIndex = 0)
    {
        var shell = new WshShell();
        var shortcut = (IWshShortcut)shell.CreateShortcut(linkPath);
        shortcut.TargetPath = targetPath;
        shortcut.Arguments = args;
        shortcut.Hotkey = hotkey;
        shortcut.Description = description;
        if (!string.IsNullOrEmpty(iconPath))
            shortcut.IconLocation = $"{iconPath}, {iconIndex}";
        shortcut.Save();
    }
}

// 用法:
// ShortcutHelper.CreateShortcut(
//     @"C:\Users\Public\Desktop\MyApp.lnk",
//     Application.ExecutablePath,
//     "/auto",
//     "CTRL+ALT+F11",
//     "自動備份工具",
//     @"%SystemRoot%\System32\Shell32.dll", 165);

熱鍵註冊注意事項

  • 熱鍵由 Explorer 註冊,需快捷方式位於「開始菜單」或「桌面」等受監控目錄才生效。
  • Hotkey 字符串不能包含空格(如 CTRL + ALT + F11 錯誤,正確 CTRL+ALT+F11)。
  • 若熱鍵衝突,後註冊者無效;建議提供設置界面讓用戶自定義。

命令行參數接收

目標程序在 Main(string[] args) 中即可接收 Arguments 指定的參數:

static void Main(string[] args)
{
    foreach (var arg in args) Console.WriteLine(arg);
    // 輸出:/out:output.txt  /sortby:date  /desc
}

總結

掌握 IWshShortcut 屬性,即可實現專業級的快捷方式部署體驗:自動創建桌面/開始菜單圖標、綁定熱鍵、預置啟動參數,大幅提升用戶便利性。

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