1 非管理员运行的程序最简单的是在C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp 路径下放入超链接即可
2 默认管理员运行的程序
(1)在程序的app.manifest中设置如下
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
(2)在程序的启动时调用如下代码
var starupPath = GetType().Assembly.Location;//获得程序路径其他方式也可以
try
{
var fileName = starupPath;
var shortFileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
//打开子键节点
var myReg = Registry.LocalMachine.OpenSubKey(
"SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run", RegistryKeyPermissionCheck.ReadWriteSubTree,
RegistryRights.FullControl);
if (myReg == null)
{
//如果子键节点不存在,则创建之
myReg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run");
}
if (myReg != null && myReg.GetValue(shortFileName) != null)
{
//在注册表中设置自启动程序
myReg.DeleteValue(shortFileName);
myReg.SetValue(shortFileName, fileName);
}
else if (myReg != null && myReg.GetValue(shortFileName) == null)
{
myReg.SetValue(shortFileName, fileName);
}
}
catch
{
}
这里需要注意的是
(1)你的程序是32位的注册表路径是
"SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Run"
(2) 你的程序是64位的注册表路径是
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
这样设置后你的程序仍然没有启动?
这时可能和你的程序调用了你程序文件夹下的文件有关系,这时可以写一个run.bat脚本,在脚本中先cd到你的程序路径,然后启动程序,最后把run.bat的超链接放在C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp中
bat的内容例子如下:
C:
cd C:\Users\user\Desktop\Debug
chcp 65001
@setlocal enableextensions enabledelayedexpansion
@echo off
set m_path="C:\Users\user\Desktop\Debug\program.exe"
echo !m_path!
echo 开始启动...
start "" !m_path!
echo "结束"
exit