将启动文件夹快捷方式添加到您的应用程序
如何使用 C# 在 Windows 启动文件夹中创建和删除快捷方式文件。
引言
本文介绍如何在 Windows 启动文件夹(或任何其他文件夹)中创建应用程序的快捷方式文件(.lnk)。如果您希望在用户登录 Windows 时启动您的应用程序,这将非常有用。示例代码还展示了如何读取快捷方式的目标文件,以确定它是否指向您的应用程序。当您想删除应用程序的现有快捷方式时,这很有用。
使用本文中的代码,您将能够在您的应用程序中添加一个复选框,标签为“在 Windows 启动时启动此应用程序”。
通过启动文件夹快捷方式在登录时启动您的应用程序比将应用程序作为服务启动更友好。它向用户显示应用程序在登录时启动,而不是许多在后台启动且只能通过 msconfig 等特殊工具禁用的更新管理器(来自 Adobe、Google、Apple)。
背景
.NET Framework 中没有用于创建和编辑 Windows 快捷方式文件的直接 API。您将不得不使用由 Windows Shell 和 Windows Script Host 公开的 COM API。此外,Microsoft 尚未记录快捷方式文件格式。
本文介绍了如何使用 COM 互操作从 C# 应用程序创建和读取快捷方式文件。
使用代码
示例代码是一个简单的 Windows Forms 应用程序,带有两个按钮:创建快捷方式和删除快捷方式,允许您测试该功能。示例应用程序是一个 Visual Studio 2010 解决方案。
您需要做的第一件事是向您的项目添加两个引用。选择添加引用,选择COM选项卡,然后选择这两个组件
- Microsoft Shell Controls and Automation
- Windows Script Host Object Model
单击“确定”,您将有两个新的引用在下面突出显示
对于每个新引用,在 Visual Studio 中打开其“属性”窗口,并将属性嵌入互操作类型从True更改为False。
如果不这样做,您将收到编译器错误:互操作类型 'IWshRuntimeLibrary.WshShellClass' 无法嵌入。请改用适用的接口。,在使用 .NET 4.0 框架时。
在 C# 源代码中,我们添加这两个 using
using IWshRuntimeLibrary;
using Shell32;
下面显示了在启动文件夹中创建快捷方式文件的代码
public void CreateStartupFolderShortcut()
{
WshShellClass wshShell = new WshShellClass();
IWshRuntimeLibrary.IWshShortcut shortcut;
string startUpFolderPath =
Environment.GetFolderPath(Environment.SpecialFolder.Startup);
// Create the shortcut
shortcut =
(IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(
startUpFolderPath + "\\" +
Application.ProductName + ".lnk");
shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.Description = "Launch My Application";
// shortcut.IconLocation = Application.StartupPath + @"\App.ico";
shortcut.Save();
}
我们使用 WshShellClass
类来创建快捷方式。快捷方式的 TargetPath
从全局 Application
对象获取。
为了确定现有的快捷方式文件是否指向我们的应用程序,我们需要能够从快捷方式文件读取 TargetPath
。这是使用以下代码完成的
public string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = Path.GetDirectoryName(shortcutFilename);
string filenameOnly = Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link =
(Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return String.Empty; // Not found
}
下面显示了搜索和删除应用程序现有快捷方式的代码
public void DeleteStartupFolderShortcuts(string targetExeName)
{
string startUpFolderPath =
Environment.GetFolderPath(Environment.SpecialFolder.Startup);
DirectoryInfo di = new DirectoryInfo(startUpFolderPath);
FileInfo[] files = di.GetFiles("*.lnk");
foreach (FileInfo fi in files)
{
string shortcutTargetFile = GetShortcutTargetFile(fi.FullName);
if (shortcutTargetFile.EndsWith(targetExeName,
StringComparison.InvariantCultureIgnoreCase))
{
System.IO.File.Delete(fi.FullName);
}
}
}
在您的应用程序中使用这些方法,您现在可以在一个标签为:在 Windows 启动时启动应用程序的复选框后面实现代码。