c#: 创建桌面快捷方式

App适配输出方式时发现问题,聊做备忘。

需要注意的是:不要直接引用Interop.IWshRuntimeLibrary.dll程序集,因为它可能是x86x64的,倘若程序以Any CPU方式编译,则它不再有适配性。

所以用com方式添加引用,得一与App目标平台一至之程序集,可解惑也。

创建代码如下:

        public static void CreateShortcutOnDesktop(string shortcutName, string description = "")
        {
            //添加引用 (com->Windows Script Host Object Model),using IWshRuntimeLibrary;
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string shortcutPath = Path.Combine(desktopPath, string.Format("{0}.lnk", shortcutName));
            if (!System.IO.File.Exists(shortcutPath))
            {
                // 获取当前应用程序目录地址
                var shell = new IWshRuntimeLibrary.WshShell();
                // 确定是否已经创建的快捷键被改名了
                foreach (var item in Directory.GetFiles(desktopPath, "*.lnk"))
                {
                    var ws = (IWshRuntimeLibrary.WshShortcut)shell.CreateShortcut(item);
                    if (ws.TargetPath == App.ExecutablePath)
                    {
                        System.IO.File.Move(item, shortcutPath);
                        return;
                    }
                }

                var shortcut = (IWshRuntimeLibrary.WshShortcut)shell.CreateShortcut(shortcutPath);
                shortcut.TargetPath = App.ExecutablePath;
                shortcut.Arguments = string.Empty;
                shortcut.Description = description;
                shortcut.WorkingDirectory = Environment.CurrentDirectory;
                shortcut.IconLocation = App.ExecutablePath;
                shortcut.WindowStyle = 1;
                shortcut.Save();
            }
        }

需要注意的是:因其中亦有File类定义,因此若要用到System.IO程序集中File,需以全名引之。

参考资料:

C#创建桌面快捷方式 - 心灵深处的那片净土 - CSDN博客

用C#创建应用程序桌面快捷方式 - luwq168的专栏 - CSDN博客

猜你喜欢

转载自www.cnblogs.com/crwy/p/10545988.html