C#创建快捷方式-转载自ConExpress
在Windows中创建快捷方式很简单,直接用右键点击文件或文件夹,选择创建快捷方式即可。如果想用C#代码的方式创建,就没有那么方便了,因为.NET框架没有提供直接创建快捷方式的方法。
首先我们看一下快捷方式是什么。对快捷方式点右键,选择属性菜单,在弹出的属性对话框的常规Tab中可以看到,文件类型是快捷方式(.lnk),所以快捷方式本质上是lnk文件。
切换到快捷方式Tab,可以看到该快捷方式的相关属性(如下图)。
- 名称:在图标后面的文本,该快捷方式的文件名称
- 目标类型:该快捷方式指向目标的类型
- 目标位置:该快捷方式指向目标的上级文件夹名称
- 目标:该快捷方式指向目标的完整路径。
- 起始位置:该快捷方式指向目标的上级文件夹完整路径。
- 快捷键:可设定快捷键打开该快捷方式,快捷键是Ctrl、Alt、Shift和字母键的组合。
- 运行方式:通过该快捷方式打开目标之后运行的窗口大小。
- 备注:对该快捷方式的备注信息,当鼠标停留在快捷方式上时会显示。
(题外话:IE的快捷方式又把我恶心到了,目标后面紧跟着360的垃圾网址。这就是运行浏览器时自动打开某个网址的一种方式,极度鄙视这种流氓行为。)
使用C#创建快捷方式就是要创建一个lnk文件,并设置相关的属性。.NET框架本身是没有提供方法的,需要引入IWshRuntimeLibrary。在添加引用对话框中搜索Windows Script Host Object Model,选择之后添加到Project的引用中。
详细代码如下:(文章来源:http://www.cnblogs.com/conexpress/p/ShortcutCreator.html)
1 using IWshRuntimeLibrary;
2 using System.IO;
3 using System;
4
5 namespace MyLibrary
6 {
7 ///
8 /// 创建快捷方式的类
9 ///
10 ///
11 public class ShortcutCreator
12 {
13 //需要引入IWshRuntimeLibrary,搜索Windows Script Host Object Model
14
15 ///
16 /// 创建快捷方式
17 ///
18 /// 快捷方式所处的文件夹
19 /// 快捷方式名称
20 /// 目标路径
21 /// 描述
22 /// 图标路径,格式为"可执行文件或DLL路径, 图标编号",
23 /// 例如System.Environment.SystemDirectory + "\\" + "shell32.dll, 165"
24 ///
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 ///
45 /// 创建桌面快捷方式
46 ///
47 /// 快捷方式名称
48 /// 目标路径
49 /// 描述
50 /// 图标路径,格式为"可执行文件或DLL路径, 图标编号"
51 ///
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 }
如果需要获取快捷方式的属性,可以调用WshShell对象的CreateShortcut方法,传入完整的快捷方式文件路径即可得到已有快捷方式的IWshShortcut实体。修改快捷方式的属性,则修改IWshShortcut实体的属性,然后调用Save方法即可。
参考资料:http://developer.51cto.com/art/200908/147760.htm
Author:Alex Leo Email:conexpress@qq.com Blog:http://conexpress.cnblogs.com/