在 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,
})
})