通过 MSI 设置,您可以轻松地为您的应用程序创建 开始菜单 快捷方式。但是当涉及到自定义安装程序设置时,您需要编写自定义代码来创建所有程序快捷方式。在 C# 中,您可以使用 Windows Script Host library 创建快捷方式。
注意:要使用Windows Script Host 库,您需要在References > COM 选项卡> Windows Script Host Object Model 下添加一个引用。
查看这篇文章了解更多信息:http://www.morgantechspace.com/2015/01/create-start-menu-shortcut-all-programs-csharp.html
仅为当前用户创建快捷方式:
string programs_path = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
string shortcutFolder = Path.Combine(programs_path, @"YourAppFolder\SampleApp");
if (!Directory.Exists(shortcutFolder))
{
Directory.CreateDirectory(shortcutFolder);
}
WshShellClass shellClass = new WshShellClass();
string settingsLink = Path.Combine(shortcutFolder, "Settings.lnk");
IWshShortcut shortcut = (IWshShortcut)shellClass.CreateShortcut(settingsLink);
shortcut.TargetPath = @"C:\Program Files\YourAppFolder\MyAppSettings.exe";
shortcut.IconLocation = @"C:\Program Files\YourAppFolder\settings.ico";
shortcut.Arguments = "arg1 arg2";
shortcut.Description = "Click to edit SampleApp settings";
shortcut.Save();
为所有用户创建快捷方式:
您可以使用 API 函数 SHGetSpecialFolderPath 获取所有用户的通用配置文件路径。
using IWshRuntimeLibrary;
using System.Runtime.InteropServices;
---------------------------------
[DllImport("shell32.dll")]
static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, bool fCreate);
const int CSIDL_COMMON_STARTMENU = 0x16;
public static void CreateShortcutForAllUsers()
{
StringBuilder allUserProfile = new StringBuilder(260);
SHGetSpecialFolderPath(IntPtr.Zero, allUserProfile, CSIDL_COMMON_STARTMENU, false);
//The above API call returns: C:\ProgramData\Microsoft\Windows\Start Menu
string programs_path = Path.Combine(allUserProfile.ToString(), "Programs");
string shortcutFolder = Path.Combine(programs_path, @"YourAppFolder\SampleApp");
if (!Directory.Exists(shortcutFolder))
{
Directory.CreateDirectory(shortcutFolder);
}
WshShellClass shellClass = new WshShellClass();
//Create Shortcut for Application Settings
string settingsLink = Path.Combine(shortcutFolder, "Settings.lnk");
IWshShortcut shortcut = (IWshShortcut)shellClass.CreateShortcut(settingsLink);
shortcut.TargetPath = @"C:\Program Files\YourAppFolder\MyAppSettings.exe";
shortcut.IconLocation = @"C:\Program Files\YourAppFolder\settings.ico";
shortcut.Arguments = "arg1 arg2";
shortcut.Description = "Click to edit SampleApp settings";
shortcut.Save();
}