通过MSI安装程序,您可以轻松地为应用程序创建开始菜单快捷方式。但是,在使用自定义安装程序时,您需要编写自定义代码来创建所有程序的快捷方式。在C#中,您可以使用Windows脚本主机库创建快捷方式。
注意:要使用Windows脚本主机库,您需要在“引用> COM选项卡> Windows脚本主机对象模型”下添加引用。
有关更多信息,请参见此文章:
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();
}