C# 创建快捷方式、获取快捷方式链接地址

这篇博客介绍了如何在C#中利用Windows Script Host Object Model来创建和读取快捷方式文件(.lnk)。通过`IWshRuntimeLibrary.WshShell`接口,可以创建快捷方式,设置目标路径、参数、描述、热键和图标,并能读取快捷方式的链接地址。
摘要由CSDN通过智能技术生成
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Sci
{
    // 添加引用 -> com组件 -> Windows Script Host Object Model
    // Interop.IWshRuntimeLibrary.dll
    class ShotCutTool
    {
        private static IWshRuntimeLibrary.WshShell shell;

        /// <summary>
        /// 为srcFile文件创建快捷方式
        /// </summary>
        /// <param name="srcFile">待创建快捷方式的文件</param>
        /// <param name="linkPath">快捷方式保存完整路径</param>
        /// <param name="arguments">快捷方式传递的参数信息</param>
        /// <param name="description">描述</param>
        /// <param name="hotkey">系统热键</param>
        /// <param name="iconLocation">快捷方式图标路径</param>
        public static void CreateShotCut(string srcFile, string linkPath = null, string arguments = null, string description = null, string hotkey = null, string iconLocation = null)
        {
            if (linkPath == null) linkPath = srcFile;
            linkPath += ".lnk";
            if (File.Exists(linkPath)) File.Delete(linkPath);               // 删除原有的lnk文件

            if(shell == null) shell = new IWshRuntimeLibrary.WshShell();
            IWshRuntimeLibrary.IWshShortcut shotcut = shell.CreateShortcut(linkPath);   // 创建一个指定名称路径的lnk
            shotcut.TargetPath = srcFile;                                               // 待创建链接的原文件

            if(arguments != null) shotcut.Arguments = arguments;            // 传递参数
            if (description != null) shotcut.Description = description;     // 链接描述
            if (hotkey != null) shotcut.Hotkey = hotkey;                    // 全局热键, 如:"CTRL+SHIFT+N"
            if (iconLocation != null) shotcut.IconLocation = iconLocation;  // 设置Icon图标

            shotcut.Save();                     // 保存link
        }

        /// <summary>
        /// 获取快捷方式的链接地址
        /// </summary>
        /// <param name="linkPath">快捷方式路径</param>
        /// <returns></returns>
        public static string GetTargetPath(string linkPath)
        {
            if (shell == null) shell = new IWshRuntimeLibrary.WshShell();
            IWshRuntimeLibrary.IWshShortcut shotcut = shell.CreateShortcut(linkPath);   // 创建一个指定名称路径的lnk

            string targetPath = shotcut.TargetPath;
            if (targetPath == null) targetPath = "";
            return targetPath;
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值