说明:
nodejs操作注册表本人试过两个库,第一个是regedit库;另外一个则是winre库。个人推荐winre库。主要是因为:
- winre库操作方便,源代码阅读方便。
- winre库支持electron-packager 打包为sar格式。
app完成功能:
- electron 开发app可以使用户通过menu来设置开机自启动。
- 支持electron-packager 打包为sar形式。
代码
-
安装:
npm install winre;
-
主要代码
let Registry = require('winreg');
let regKey = new Registry({ // new operator is optional
hive: Registry.HKCU, // open registry hive HKEY_CURRENT_USER
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' // key containing autostart programs
});
regKey.get("runAppClient",function (err, item) {
if (err)
console.log('ERROR: '+err);
menu.append(new MenuItem({
label: '开机自启动',
type: 'checkbox',
checked: item!==null&&item.value!==undefined,
click: function (currentMenu) {
let value = "";
if (currentMenu.checked)
value = "\"" + path.join(process.env.appclient, "appclient.exe") + "\"";
regKey.set("runAppformClient", "REG_SZ", value, function (err, item) {
if (err)
console.log('ERROR: ' + err);
else
console.log("sucess");
});
}
}));
});
-
winre库说明:
通过阅读代码发现,winre实际上是封装了一层windows的reg的命令行,所有操作注册表的方式都是通过命令行实现的。他的源码比较直观,所以如果需要使用什么接口,可以直接阅读源码。下面介绍两个我用到的接口:
regKey.set("runAppformClient", "REG_SZ", value, function (err, item){})
设置runAppformClient的值为value,value的type为REG_SZ,最后一个为回调函数。这里有一点需要注意的是,如果该值不存在,则会新建runAppformClient。
regKey.get("runAppClient",function (err, item) {})
获取runAppClient的value值,如果该值不存在,则在回调函数中的err的code为-1。