前言
快捷方式是一種特殊的文件,擴展名為 lnk。有很多種方式來創建快捷方式,首先我們看一下快捷方式是什么。對快捷方式點右鍵,選擇屬性菜單,在彈出的屬性對話框的常規tab中可以看到,文件類型是快捷方式(.lnk),所以快捷方式本質上是lnk文件。
不過使用 c# 代碼創建一個卻并不那么容易,本文分享三種不同的方式創建快捷方式。
隨處可用的代碼
這是最方便的方式了,因為這段代碼隨便放到一段代碼中就能運行:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/// <summary> /// 為當前正在運行的程序創建一個快捷方式。 /// </summary> /// <param name="lnkfilepath">快捷方式的完全限定路徑。</param> /// <param name="args">快捷方式啟動程序時需要使用的參數。</param> private static void createshortcut( string lnkfilepath, string args = "" ) { var shelltype = type.gettypefromprogid( "wscript.shell" ); dynamic shell = activator.createinstance(shelltype); var shortcut = shell.createshortcut(lnkfilepath); shortcut.targetpath = assembly.getentryassembly().location; shortcut.arguments = args; shortcut.workingdirectory = appdomain.currentdomain.setupinformation.applicationbase; shortcut.save(); } |
以上代碼為當前正在運行的程序創建一個快捷方式。當然,如果你希望給其他文件創建快捷方式,就改一改里面的代碼吧,將 targetpath 和 workingdirectory 改為其他參數。
▲ 快捷方式屬性(其中 target 等同于上面的 targetpath 和 arguments 一起,start in 等同于上面的 workingdirectory)
引用 com 組件
引用 com 組件 interop.iwshruntimelibrary.dll 能夠獲得類型安全,不過本質上和以上方法是一樣的。
1
2
3
4
5
6
7
8
9
|
private static void createshortcut( string lnkfilepath, string args = "" ) { var shell = new iwshruntimelibrary.wshshell(); var shortcut = (iwshruntimelibrary.iwshshortcut) shell.createshortcut(linkfilename); shortcut.targetpath = assembly.getentryassembly().location; shortcut.arguments = args; shortcut.workingdirectory = appdomain.currentdomain.setupinformation.applicationbase; shortcut.save(); } |
兼容 .net 3.5 或早期版本
如果你還在使用 .net framework 3.5 或更早期版本,那真的很麻煩。同情你以下,不過也貼一段代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
private static void createshortcut( string lnkfilepath, string args = "" ) { var shelltype = type.gettypefromprogid( "wscript.shell" ); var shell = activator.createinstance(shelltype); var shortcut = shelltype.invokemember( "createshortcut" , bindingflags. public | bindingflags.instance | bindingflags.invokemethod, null , shell, new object [] { linkfilename }); var shortcuttype = shortcut.gettype(); shortcuttype.invokemember( "targetpath" , bindingflags. public | bindingflags.instance | bindingflags.setproperty, null , shortcut, new object [] { assembly.getentryassembly().location }); shortcuttype.invokemember( "arguments" , bindingflags. public | bindingflags.instance | bindingflags.setproperty, null , shortcut, new object [] { args }); shortcuttype.invokemember( "workingdirectory" , bindingflags. public | bindingflags.instance | bindingflags.setproperty, null , shortcut, new object [] { appdomain.currentdomain.setupinformation.applicationbase }); shortcuttype.invokemember( "save" , bindingflags. public | bindingflags.instance | bindingflags.invokemethod, null , shortcut, null ); } |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://walterlv.github.io/post/create-shortcut-file-using-csharp.html