You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Visual Studio 2022中实现安装时添加应用快捷方式到启动文件夹

在Visual Studio 2022的C#应用安装时添加快捷方式到启动文件夹

方法一:使用Microsoft Visual Studio Installer Projects扩展

这是可视化配置的常规方案,操作简单:

  • 打开Visual Studio 2022,通过「工具」->「扩展和更新」搜索安装「Microsoft Visual Studio Installer Projects」,重启VS生效。
  • 右键解决方案,选择「添加」->「新建项目」,创建「Setup Project」(Windows安装程序项目)。
  • 右键安装项目,选择「添加」->「项目输出」,选中你的C#主项目的「主输出」并确认。
  • 在安装项目的「文件系统」视图中,右键刚才添加的「主输出」,选择「创建快捷方式」,给快捷方式命名(比如你的应用名称)。
  • 在文件系统视图左侧找到「用户的启动」(仅当前用户生效)或「所有用户的启动」(所有用户登录时启动)文件夹,将创建好的快捷方式拖入该文件夹。
  • 配置安装项目的目标平台、默认安装路径等参数,生成安装包后,运行安装程序即可自动在启动文件夹添加快捷方式。

方法二:自定义安装程序类(代码实现)

适合需要灵活控制安装逻辑的场景:

  • 在你的C#项目中添加安装程序类:右键项目->「添加」->「新建项」->选中「安装程序类」。
  • 重写Install方法实现快捷方式创建,可同时重写Uninstall方法处理卸载时的清理:
using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using IWshRuntimeLibrary;

[RunInstaller(true)]
public class AppInstaller : Installer
{
    public override void Install(System.Collections.IDictionary stateSaver)
    {
        base.Install(stateSaver);

        // 获取应用程序可执行文件路径
        string appExePath = Context.Parameters["assemblypath"];
        if (string.IsNullOrEmpty(appExePath))
            appExePath = Path.Combine(Context.Parameters["targetdir"], "你的应用程序.exe");

        // 选择启动文件夹:当前用户或所有用户
        string startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
        // string startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup); // 所有用户生效

        // 创建快捷方式
        string shortcutPath = Path.Combine(startupFolder, "你的应用程序.lnk");
        WshShell shell = new WshShell();
        IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
        shortcut.TargetPath = appExePath;
        shortcut.WorkingDirectory = Path.GetDirectoryName(appExePath);
        shortcut.Description = "你的应用程序启动快捷方式";
        shortcut.IconLocation = appExePath;
        shortcut.Save();
    }

    public override void Uninstall(System.Collections.IDictionary savedState)
    {
        base.Uninstall(savedState);

        string startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
        string shortcutPath = Path.Combine(startupFolder, "你的应用程序.lnk");
        if (File.Exists(shortcutPath))
            File.Delete(shortcutPath);
    }
}
  • 右键项目选择「添加引用」,在COM标签页找到「Windows Script Host Object Model」并勾选引用。
  • 通过ClickOnce或第三方安装工具打包应用,确保安装过程中调用该安装程序类。若使用ClickOnce,需在项目属性的「发布」选项中配置安装模式,触发自定义安装逻辑。

注意事项

  • 若要添加到「所有用户的启动」文件夹,安装程序需具备管理员权限,可在项目属性的「安全性」中设置「RequireAdministrator」。
  • 安装完成后务必测试:检查启动文件夹的快捷方式,重启验证应用自启动效果,卸载时确认快捷方式被删除。

内容的提问来源于stack exchange,提问作者Daniel Heikkilä

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 06:42:55