在 Electron 中,可以使用 auto-launch 模块来设置开机自启动和关闭自启动。

首先,需要安装 auto-launch 模块:

npm install auto-launch --save

然后,在主进程中引入该模块,并创建一个 AutoLaunch 实例:

const AutoLaunch = require('auto-launch');

const appAutoLauncher = new AutoLaunch({
    name: 'MyApp', // 应用名称
    path: process.execPath // 应用程序路径
});

接下来,可以使用 isEnabled() 方法来检查应用是否已设置为开机自启动:

appAutoLauncher.isEnabled()
    .then((isEnabled) => {
        console.log('Auto launch status:', isEnabled);
    })
    .catch((err) => {
        console.error(err);
    });

如果应用已设置为开机自启动,则返回 true,否则返回 false

要设置应用为开机自启动,可以使用 enable() 方法:

appAutoLauncher.enable()
    .then(() => {
        console.log('Auto launch enabled');
    })
    .catch((err) => {
        console.error(err);
    });

要关闭应用的开机自启动,可以使用 disable() 方法:

appAutoLauncher.disable()
    .then(() => {
        console.log('Auto launch disabled');
    })
    .catch((err) => {
        console.error(err);
    });

注意:在 Windows 上,需要管理员权限才能设置开机自启动。如果没有管理员权限,则会抛出错误

electron 设置开机自启动和关闭自启动

原文地址: https://www.cveoy.top/t/topic/c3oV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录