C#设置程序开机自启动[需登录]

C#设置程序开机自启动[需登录]

写在前面

本来是想在服务器上实现服务器崩溃或者更新后,可以自动启动winform程序,但是以下方法还是需要有用户登录进去。

方法一:将软件的快捷方式创建到计算机的自动启动目录下(不需要管理员权限)

  1. 进入目录:C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
  2. 将应用程序快捷方式剪切(或者复制)并粘贴到目录中
  3. 应用程序快捷方式加入到了启动项,下次重启电脑之后这个应用程序就会自动开机运行了

如果需要针对个人账户进行配置:Win+R输入命令shell:startup ,会直接弹出启动项对应的目录,然后像前面方法一样把应用程序快捷方式复制到启动目录

方法二:修改计算机注册表的方式(需要管理员权限)

开始

Windows自启动原理

在Windows操作系统下,主要有2个文件夹和8个注册表键项控制程序的自启动,通过修改“Run”键值实现自启动程序是比较常见的方法。
具体的位置是:HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Run

代码

在知道注册表中自启动位置所在后,只需要将需要启动的程序路径添加至指定路径中就可以实现开机自启动功能。

Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
using (Mutex mutex = new Mutex(false, "Global\\" + appGuid))
{
if (!mutex.WaitOne(0, false))
{
return;
}
//判断是否开启自启动
string strFilePath = Application.ExecutablePath;
string strFileName = System.IO.Path.GetFileName(strFilePath);
try
{
//自启动功能是否开启
var AutoRunFlag = ConfigurationManager.AppSettings["AutoRunFlag"] == "1" ? true : false;
//自启动是否已经存在
var flag = SystemHelper.IsAutoRun(strFilePath, strFileName);
if (AutoRunFlag != flag)
{
#region 获取管理员权限,进行注册表写入操作
//当前用户是管理员的时候,直接启动应用程序并且写入注册表
//如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
//获得当前登录的Windows用户标示
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
try
{
//如果是管理员,注册自启动代码
SystemHelper.SetAutoRun(strFilePath, strFileName, AutoRunFlag);
}
catch(Exception ex)
{
MessageBox.Show( ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
try
{
System.Diagnostics.Process.Start(startInfo);
}
catch
{
return;
}
//退出
Application.Exit();
}
#endregion
}
//启动程序
Application.Run(new Form1());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return;
}
}


}

SystemHelper.cs 参考自:C# winform程序实现开机自启动,并且识别是开机启动还是双击启动

SystemHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public sealed class SystemHelper
{
private SystemHelper() { }
/// <summary>
/// 设置程序开机启动
/// </summary>
/// <param name="strAppPath">应用程序exe所在文件夹</param>
/// <param name="strAppName">应用程序exe名称</param>
/// <param name="bIsAutoRun">自动运行状态</param>
public static void SetAutoRun(string strAppPath, string strAppName, bool bIsAutoRun)
{
try
{
if (string.IsNullOrWhiteSpace(strAppPath)
|| string.IsNullOrWhiteSpace(strAppName))
{
throw new Exception("应用程序路径或名称为空!");
}
RegistryKey reg = Registry.LocalMachine;
RegistryKey run = reg.CreateSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");
if (bIsAutoRun)
{
run.SetValue(strAppName, strAppPath);
}
else
{
if (null != run.GetValue(strAppName))
{
run.DeleteValue(strAppName);
}
}
run.Close();
reg.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// 判断是否开机启动
/// </summary>
/// <param name="strAppPath">应用程序路径</param>
/// <param name="strAppName">应用程序名称</param>
/// <returns></returns>
public static bool IsAutoRun(string strAppPath, string strAppName)
{
try
{
RegistryKey reg = Registry.LocalMachine;
RegistryKey software = reg.OpenSubKey(@"SOFTWARE");
RegistryKey run = reg.OpenSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");
object key = run.GetValue(strAppName);
software.Close();
run.Close();
if (null == key || !strAppPath.Equals(key.ToString()))
{
return false;
}
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
}

运行环境

Win10
.NET Framework4.5
VS2019

填坑

  1. 注册表地址
    使用代码修改注册表的方式,如果需要查看注册信息,需要确认程序是32-bit还是64-bit。
    32位,查看地址为 :HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVers ion\Run
    64位,查看地址为 :HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

    操作系统 64位程序访问的注册表 32位程序访问的注册表
    64位系统 HKEY_LOCAL_MACHINE\SOFTWARE HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node
    32位系统 - HKEY_LOCAL_MACHINE\SOFTWARE

    参考资料:

  2. 以管理员权限打开程序:
    参考资料:

作者

zhang

发布于

2021-07-16

更新于

2023-09-19

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×