WPF 管理员权限下软件的自启动
WPF 管理员权限下软件的自启动
一、项目app.manifest种设置权限等级为requireAdministrator
二、代码实现
/// <summary>
/// 自启动实现,其中App.exe可为具体exe
/// </summary>
public void RunAtStart()
{
var starupPath = GetType().Assembly.Location;
try
{
var fileName = Path.GetDirectoryName(starupPath)+ "\\App.exe";
var shortFileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
var myReg = Registry.LocalMachine.OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", RegistryKeyPermissionCheck.ReadWriteSubTree,
RegistryRights.FullControl);
if (myReg == null)
{
myReg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\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
{
}
}
以上代码将把要自启动的软件路径写到注册表后,由windows自启动功能来实现对路径下的exe实现自启动。
三、windos本地配置设置
配置顺序如下图所示:
命令启动本地组策略编辑器
修改管理员账户状态相关设置