原理简介

本文参考C#/WPF/WinForm/程序实现软件开机自动启动的两种常用方法,将里面中的第一种方法做了封装成AutoStart类,使用时直接两三行代码就可以搞定。

自启动的原理是将软件的快捷方式创建到计算机的自动启动目录下(不需要管理员权限),这种方法更加通用、限制更少。

使用方法

使用方法如下:

//快捷方式的描述、名称的默认值是当前的进程名,自启动默认为正常窗口,一般情况下不需要手动设置
//设置快捷方式的描述,
AutoStart.Instance.QuickDescribe = "软件描述";
//设置快捷方式的名称
AutoStart.Instance.QuickName = "软件名称";
//设置自启动的窗口类型,后台服务类的软件可以设置为最小窗口
AutoStart.Instance.WindowStyle = WshWindowStyle.WshMinimizedFocus; //快捷方式设置true时,有就忽略、没有就创建,自启动快捷方式只能存在一个
//设置开机自启动,true 自启动,false 不自启动
AutoStart.Instance.SetAutoStart(SysParam.Instance.OnOff);
//设置桌面快捷方式,true 创建桌面快捷方式(有就跳过,没有就创建),false 删除桌面快捷方式
AutoStart.Instance.SetDesktopQuick(true);

完整代码

引用以下命名空间:

//添加引用,在 Com 中搜索 Windows Script Host Object Model
using IWshRuntimeLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

AutoStart类代码:

public class AutoStart
{
#region 公开 /// <summary>
/// 唯一实例,也可以自定义实例
/// </summary>
public static AutoStart Instance { get; private set; } = new AutoStart(); /// <summary>
/// 快捷方式描述,默认值是当前的进程名
/// </summary>
public string QuickDescribe { get; set; } = Process.GetCurrentProcess().ProcessName; /// <summary>
/// 快捷方式名称,默认值是当前的进程名
/// </summary>
public string QuickName { get; set; } = Process.GetCurrentProcess().ProcessName; /// <summary>
/// 自启动窗口类型,默认值是正常窗口
/// </summary>
public WshWindowStyle WindowStyle { get; set; } = WshWindowStyle.WshNormalFocus; /// <summary>
/// 设置开机自动启动-只需要调用改方法就可以了参数里面的bool变量是控制开机启动的开关的,默认为开启自启启动
/// </summary>
/// <param name="onOff">自启开关</param>
public void SetAutoStart(bool onOff = true)
{
if (onOff)//开机启动
{
//获取启动路径应用程序快捷方式的路径集合
List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
//存在2个以快捷方式则保留一个快捷方式-避免重复多于
if (shortcutPaths.Count >= 2)
{
for (int i = 1; i < shortcutPaths.Count; i++)
{
DeleteFile(shortcutPaths[i]);
}
}
else if (shortcutPaths.Count < 1)//不存在则创建快捷方式
{
CreateShortcut(systemStartPath, QuickName, appAllPath, QuickDescribe,WindowStyle);
}
}
else//开机不启动
{
//获取启动路径应用程序快捷方式的路径集合
List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);
//存在快捷方式则遍历全部删除
if (shortcutPaths.Count > 0)
{
for (int i = 0; i < shortcutPaths.Count; i++)
{
DeleteFile(shortcutPaths[i]);
}
}
}
//创建桌面快捷方式-如果需要可以取消注释
//CreateDesktopQuick(desktopPath, QuickName, appAllPath);
} /// <summary>
/// 在桌面上创建快捷方式-如果需要可以调用
/// </summary>
public void SetDesktopQuick(bool isCreate)
{
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
List<string> shortcutPaths = GetQuickFromFolder(desktopPath, appAllPath);
if (isCreate)
{
//没有就创建
if (shortcutPaths.Count < 1)
{
CreateShortcut(desktopPath, QuickName, appAllPath, QuickDescribe, WshWindowStyle.WshNormalFocus);
}
}
else
{
//有就删除
for (int i = 0; i < shortcutPaths.Count; i++)
{
DeleteFile(shortcutPaths[i]);
}
}
} #endregion 公开 #region 私有 /// <summary>
/// 自动获取系统自动启动目录
/// </summary>
private string systemStartPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); /// <summary>
/// 自动获取程序完整路径
/// </summary>
private string appAllPath = Process.GetCurrentProcess().MainModule.FileName; /// <summary>
/// 自动获取桌面目录
/// </summary>
private string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); /// <summary>
/// 向目标路径创建指定文件的快捷方式
/// </summary>
/// <param name="directory">目标目录</param>
/// <param name="shortcutName">快捷方式名字</param>
/// <param name="targetPath">文件完全路径</param>
/// <param name="description">描述</param>
/// <param name="iconLocation">图标地址</param>
/// <returns>成功或失败</returns>
private bool CreateShortcut(string directory, string shortcutName, string targetPath, string description, WshWindowStyle windowStyle, string iconLocation = null)
{
try
{
//目录不存在则创建
if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
//合成路径
string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
//存在则不创建
if (System.IO.File.Exists(shortcutPath)) return true;
//添加引用 Com 中搜索 Windows Script Host Object Model
WshShell shell = new IWshRuntimeLibrary.WshShell();
//创建快捷方式对象
IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);
//指定目标路径
shortcut.TargetPath = targetPath;
//设置起始位置
shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);
//设置运行方式,默认为常规窗口
shortcut.WindowStyle = (int)windowStyle;
//设置备注
shortcut.Description = description;
//设置图标路径
shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;
//保存快捷方式
shortcut.Save();
return true;
}
catch (Exception ex)
{
string temp = ex.Message;
temp = "";
}
return false;
} /// <summary>
/// 获取指定文件夹下指定应用程序的快捷方式路径集合
/// </summary>
/// <param name="directory">文件夹</param>
/// <param name="targetPath">目标应用程序路径</param>
/// <returns>目标应用程序的快捷方式</returns>
private List<string> GetQuickFromFolder(string directory, string targetPath)
{
List<string> tempStrs = new List<string>();
tempStrs.Clear();
string tempStr = null;
string[] files = Directory.GetFiles(directory, "*.lnk");
if (files == null || files.Length < 1)
{
return tempStrs;
}
for (int i = 0; i < files.Length; i++)
{
//files[i] = string.Format("{0}\\{1}", directory, files[i]);
tempStr = GetAppPathFromQuick(files[i]);
if (tempStr == targetPath)
{
tempStrs.Add(files[i]);
}
}
return tempStrs;
} /// <summary>
/// 获取快捷方式的目标文件路径-用于判断是否已经开启了自动启动
/// </summary>
/// <param name="shortcutPath"></param>
/// <returns></returns>
private string GetAppPathFromQuick(string shortcutPath)
{
//快捷方式文件的路径 = @"d:\Test.lnk";
if (System.IO.File.Exists(shortcutPath))
{
WshShell shell = new WshShell();
IWshShortcut shortct = (IWshShortcut)shell.CreateShortcut(shortcutPath);
//快捷方式文件指向的路径.Text = 当前快捷方式文件IWshShortcut类.TargetPath;
//快捷方式文件指向的目标目录.Text = 当前快捷方式文件IWshShortcut类.WorkingDirectory;
return shortct.TargetPath;
}
else
{
return "";
}
} /// <summary>
/// 根据路径删除文件-用于取消自启时从计算机自启目录删除程序的快捷方式
/// </summary>
/// <param name="path">路径</param>
private void DeleteFile(string path)
{
FileAttributes attr = System.IO.File.GetAttributes(path);
if (attr == FileAttributes.Directory)
{
Directory.Delete(path, true);
}
else
{
System.IO.File.Delete(path);
}
} #endregion 私有
}

C#实现软件开机自启动(不需要管理员权限)的更多相关文章

  1. Qt之开机自启动及拥有管理员权限

    源地址:http://blog.sina.cn/dpool/blog/s/blog_a6fb6cc90101feia.html Windows开机自启动的程序很多,包括系统软件.杀毒软件.一些其他安装 ...

  2. VC++ 设置软件开机自启动的方法

    0  概述 软件开机自启动是比较常用的做法,设置方法也有好几种. 1  使用者模式 在"开始菜单"的所有程序中有个"启动"文件夹,可以将需要设置为开机启动的应用 ...

  3. C#实现软件开机自启动原理与代码

    1.软件自启动原理 软件自启动的原理要从Windows的注册表聊起,在Windows操作系统下,主要有2个文件夹和8个注册表键项控制程序的自启动,这部分的详细介绍可以参看博客http://www.cn ...

  4. windows平板软件开机自启动+霸屏的操作方法

        转载(忘了地址) 很好很强大.成功亲测 使用你自己的账号(最好是管理员权限的账号)登录Windows,然后添加一个给其他人使用的账户(假设为other),注意一定要为other设置密码. 运行 ...

  5. android 软件开机自启动

    安卓的很多功能实现方式都是“Don't call me, I'll call you back!”,开机启动就是其中之一 步骤: 1.首先建立一个BroadcastReceiver, 2.在他的onR ...

  6. win7解压的软件开机自启动

    win7让你一个可执行程序开机启动. 运行-->regedit-->HKEY_LOCAL_MACHINE-->SOFTWARE-->Microsoft-->Windows ...

  7. 如何使一个openwrt下的软件开机自启动

    条件有三: 1.需要在软件包的Makefile中添加宏定义Package/$(package-name)/preinst和Package/$(package-name)/prerm define Pa ...

  8. [Winform]setupfactory打包时添加开机自启动的脚本

    摘要 如果有这样的需求,需要软件开机自启动,该如何做呢?开机自启动的做法,就是修改注册表,将你的exe注册到注册表Run节点下. setupfactory 在安装的时候需要以管理员身份运行,这样可以保 ...

  9. tomcat7 开机自启动(转)

    转自 http://blog.csdn.net/rainyspring4540/article/details/51861079 环境:win7  tomcat7 开机自启动: 使用管理员打开命令提示 ...

  10. Mac Pro 开机自启动 PHP-FPM,Nginx,MySql 等软件

    在Mac下安装好了PHP开发环境(PHP-FPM,Nginx,MySql), 想设置成开机自启动,原来以为和一般的Linux系统一样,也是在rc.d这样目录放置启动脚本.在网上查了一些资料,发现苹果应 ...

随机推荐

  1. 21.13 Python 实现端口流量转发

    端口流量转发(Port Forwarding)是一种网络通信技术,用于将特定的网络流量从一个端口或网络地址转发到另一个端口或地址.它在网络中扮演着一个非常重要的角色,在Python语言中实现端口转发非 ...

  2. 1.5 为x64dbg编写插件

    任何一个成熟的软件都会具有可扩展性,可扩展性是现代软件的一个重要特征,因为它使软件更易于维护和适应变化的需求,x64dbg也不例外其可通过开发插件的方式扩展其自身功能,x64dbg提供了多种插件接口, ...

  3. 8.9 RDTSC时钟检测反调试

    RDTSC时钟检测同样可实现反调试检测,使用时钟检测方法是利用rdtsc汇编指令,它返回至系统重新启动以来的时钟数,并且将其作为一个64位的值存入EDX:EAX寄存器中,通过运行两次rdstc指令,然 ...

  4. Java Calendar 多用,日期 加减

    服务需要订购一个月,订购一个月 不等于增加 30天:若是1,3,5的话应该 31天,要善用 Calendar public static void main(String[] args) throws ...

  5. JS 数组中找到与目标值最接近的数字,记一次工作中关于二分查找的算法优化

    壹 ❀ 引 在最近的工作中,有一个任务是需要修复富文本编辑器字号显示的BUG.大概情况就是,从WPS中复制不同样式的标题.正文到到项目编辑器中,发现没办法设置选中的文本为正文:而且字体字号都显示为默认 ...

  6. k8s-权限管理

    目录 1. 身份认证 node节点操作 创建普通用户并授权 1. 生成私钥 2. 生成zhangsan用户证书请求文件 3. 为zhangsan用户颁发证书 4. 创建命名空间及pod 5. 创建角色 ...

  7. CSS实现图形效果

    CSS实现图形效果 CSS实现正方形.长方形.圆形.半圆.椭圆.三角形.平行四边形.菱形.梯形.六角星.五角星.心形.消息框. 正方形 <section> <div id=" ...

  8. Swoole从入门到入土(28)——协程[核心API]

    本节专门介绍swoole提供的协程机制中核心的API 类方法: 1) set():协程设置,设置协程相关选项. Swoole\Coroutine::set(array $options); 2) ge ...

  9. 2024-02-24:用go语言,给你一个 n 个点的带权无向连通图,节点编号为 0 到 n-1, 同时还有一个数组 edges ,其中 edges[i] = [fromi, toi, weighti

    2024-02-24:用go语言,给你一个 n 个点的带权无向连通图,节点编号为 0 到 n-1, 同时还有一个数组 edges ,其中 edges[i] = [fromi, toi, weighti ...

  10. Jenkins共享库使用

    简单使用 共享库(Shared libraries)是一种可以用来封装函数.变量甚至整个 Pipeline 的机制.通过共享库,可以将常用的功能和流程逻辑定义在单独的 Groovy 脚本中,然后在多个 ...