如何使用C#操作快捷方式(获取快捷方式属性、创建快捷方式)

近来项目中有需要用到一个技术:使用C#操控快捷方式,包含创建和读取等。现整理一下实现方式,分享给大家。

第一步  创建一个项目

无需废话,跳过。

第二步  引用COM组件

右键“引用”,“添加引用”,选择“COM组件”,找到“Windows Script Host Object Model”,然后确定。

第三步  编写创建快捷方式的代码

创建快捷方式
// 声明操作对象
IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShellClass();
// 创建一个快捷方式
IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut("c:\yeaicc.lnk");
// 关联的程序
shortcut.TargetPath = "notepad.exe";
// 参数
shortcut.Arguments = "c:\yeaicc.txt";
// 快捷方式描述,鼠标放到快捷方式上会显示出来哦
shortcut.Description = "我的快捷方式--yeaicc";
// 全局热键
shortcut.Hotkey = "CTRL+SHIFT+N";
// 设置快捷方式的图标,这里是取程序图标,如果希望指定一个ico文件,那么请写路径。
shortcut.IconLocation = "notepad.exe, 0";
// 保存,创建就成功了。
shortcut.Save();

第四步  读取快捷方式属性

IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShellClass();
IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut("c:\yeaicc.lnk");
// 亲,根据刚刚创建时的代码,你想获取什么属性?
MessageBox.Show(ws.Description);

================================分割线============================================

C# 创建快捷方式 以下代码在2.0,3.0,3.5 下都可以正常运行,在4.0在报错。

不知道那为仁兄知道在4.0下创建快捷方式。

选择 COM 选项卡并选择 Windows Script Host Object Model
using IWshRuntimeLibrary;



namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            string DesktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);//得到桌面文件夹 

            WshShell shell = new WshShell();



            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(DesktopPath + "\自动创建+.lnk");

            shortcut.TargetPath = @"%HOMEDRIVE%/Program FilesInternet ExplorerIEXPLORE.EXE";

            shortcut.Arguments = "http://www.baidu.com";// 参数 

            shortcut.Description = "快捷链接到网站";

            shortcut.WorkingDirectory = "E:\Publish Web Site\clcs";//程序所在文件夹,在快捷方式图标点击右键可以看到此属性 

            shortcut.IconLocation = @"%HOMEDRIVE%/Program FilesInternet ExplorerIEXPLORE.EXE, 0";//图标 

            shortcut.Hotkey = "CTRL+SHIFT+Z";//热键 

            shortcut.WindowStyle = 1;

            shortcut.Save();



        }

    }

}
原文地址:https://www.cnblogs.com/DoNetCShap/p/4221839.html