相关链接
三种方法
第一种:开始菜单启动
- 原理: 将应用程序的可执行文件的快捷方式复制到系统或者用户的菜单启动目录下即可
- 前提条件:需要引入com组件 Windows Script Host Object Model
- 核心代码
public static bool Create(string directory, string shortcutName, string targetPath,
string description = null, string iconLocation = null)
{
try
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
//添加引用 Com 中搜索 Windows Script Host Object Model
string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象
shortcut.TargetPath = targetPath;//指定目标路径
shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
shortcut.WindowStyle = 1;//设置运行方式,默认为常规窗口
shortcut.Description = description;//设置备注
shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
shortcut.Save();//保存快捷方式
return true;
}
catch
{ }
return false;
}
/// <summary>
/// 通过创建快捷方式并放到菜单启动根目录下实现 开机自启动
/// </summary>
private void AutoRunFun1()
{
// 通过创建快捷方式并放到菜单启动根目录下实现 开机自启动
var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
var currentDirectory = Directory.GetCurrentDirectory();
var str = Path.Combine(currentDirectory, "AutoRunApplication.exe");
try
{
Create(startupPath, "AutoRunApplication", str);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
private void CancelAutoRunFun1()
{
var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
startupPath = Path.Combine(startupPath, "AutoRunApplication.lnk");
if (File.Exists(startupPath))
{
File.Delete(startupPath);
}
}
第二种:注册表开机启动项
// 添加到 当前登陆用户的 注册表启动项
RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
RKey.SetValue("AppName", """" +@"C:\AppName.exe" + """");
RegistryKey rKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
rKey.DeleteValue("autorunapp");
第三种:Windows 计划任务方式启动
网友评论