electron 应用超管权限自启动

在 Windows 上,可以使用任务计划来设置应用程序开机自启,并以管理员权限运行。可以使用 node-schedule 等库来创建任务计划。

首先,安装 node-schedule 库:

npm install node-schedule
const { app } = require('electron');
const schedule = require('node-schedule');
const { exec } = require('child_process');
app.on('ready', () => {
  // 获取应用的可执行文件路径
  const exePath = app.getPath('exe');
  
// 修改为自己的应用名称
  const taskName = 'xxxx'

  // 定义任务计划的 XML
  const taskXml = `
   <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
     <RegistrationInfo>
       <Date>${new Date().toISOString()}</Date>
       <Author>${process.env.USERNAME}</Author>
     </RegistrationInfo>
     <Triggers>
       <LogonTrigger>
         <Enabled>true</Enabled>
       </LogonTrigger>
     </Triggers>
     <Principals>
       <Principal id="Author">
         <LogonType>InteractiveToken</LogonType>
         <RunLevel>HighestAvailable</RunLevel>
       </Principal>
     </Principals>
     <Settings>
       <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
       <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
       <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
       <AllowHardTerminate>false</AllowHardTerminate>
       <StartWhenAvailable>true</StartWhenAvailable>
       <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
       <IdleSettings>
         <StopOnIdleEnd>false</StopOnIdleEnd>
         <RestartOnIdle>false</RestartOnIdle>
       </IdleSettings>
       <AllowStartOnDemand>true</AllowStartOnDemand>
       <Enabled>true</Enabled>
       <Hidden>false</Hidden>
       <RunOnlyIfIdle>false</RunOnlyIfIdle>
       <WakeToRun>false</WakeToRun>
       <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
       <Priority>7</Priority>
     </Settings>
     <Actions Context="Author">
       <Exec>
         <Command>${exePath}</Command>
       </Exec>
     </Actions>
   </Task>
 `

  // 保存任务计划的 XML 文件
  const fs = require('fs')
  const taskFilePath = `${app.getPath('userData')}\\${taskName}.xml`
  fs.writeFileSync(taskFilePath, taskXml)

  // 使用 schtasks 命令创建任务计划
  exec(
    `schtasks /create /tn "${taskName}" /xml "${taskFilePath}" /f`,
    (error, stdout, stderr) => {
      if (error) {
        console.error(`Error creating scheduled task: ${error.message}`)
      } else {
        console.log(`Scheduled task created: ${stdout}`)
      }
    }
  )
   app.setLoginItemSettings({
    openAtLogin: true,
    path: exePath,
  })
  })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值