欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何在C#中快速创建桌面快捷方式

最编程 2024-02-22 19:43:43
...
1 using IWshRuntimeLibrary; 2 using System.IO; 3 using System; 4 5 namespace MyLibrary 6 { 7 /// <summary> 8 /// 创建快捷方式的类 9 /// </summary> 10 /// <remarks></remarks> 11 public class ShortcutCreator 12 { 13 //需要引入IWshRuntimeLibrary,搜索Windows Script Host Object Model 14 15 /// <summary> 16 /// 创建快捷方式 17 /// </summary> 18 /// <param name="directory">快捷方式所处的文件夹</param> 19 /// <param name="shortcutName">快捷方式名称</param> 20 /// <param name="targetPath">目标路径</param> 21 /// <param name="description">描述</param> 22 /// <param name="iconLocation">图标路径,格式为"可执行文件或DLL路径, 图标编号", 23 /// 例如System.Environment.SystemDirectory + "\\" + "shell32.dll, 165"</param> 24 /// <remarks></remarks> 25 public static void CreateShortcut(string directory, string shortcutName, string targetPath, 26 string description = null, string iconLocation = null) 27 { 28 if (!System.IO.Directory.Exists(directory)) 29 { 30 System.IO.Directory.CreateDirectory(directory); 31 } 32 33 string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName)); 34 WshShell shell = new WshShell(); 35 IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象 36 shortcut.TargetPath = targetPath;//指定目标路径 37 shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置 38 shortcut.WindowStyle = 1;//设置运行方式,默认为常规窗口 39 shortcut.Description = description;//设置备注 40 shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径 41 shortcut.Save();//保存快捷方式 42 } 43 44 /// <summary> 45 /// 创建桌面快捷方式 46 /// </summary> 47 /// <param name="shortcutName">快捷方式名称</param> 48 /// <param name="targetPath">目标路径</param> 49 /// <param name="description">描述</param> 50 /// <param name="iconLocation">图标路径,格式为"可执行文件或DLL路径, 图标编号"</param> 51 /// <remarks></remarks> 52 public static void CreateShortcutOnDesktop(string shortcutName, string targetPath, 53 string description = null, string iconLocation = null) 54 { 55 string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//获取桌面文件夹路径 56 CreateShortcut(desktop, shortcutName, targetPath, description, iconLocation); 57 } 58 59 } 60 }