c#: 创建桌面快捷方式

博客记录了App适配输出方式时遇到的问题。指出不要直接引用Interop.IWshRuntimeLibrary.dll程序集,因其可能无适配性,建议用com方式添加引用获取适配程序集。还提到使用System.IO程序集中File需用全名引用,并给出参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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#创建桌面快捷方式 - 心灵深处的那片净土 - 优快云博客

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

转载于:https://www.cnblogs.com/crwy/p/10545988.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值