electron 写入注册表 实现开机自启动

windows平台

首先先明确;开机自启动写入注册表的位置,在KEY_CURRENT_USERSoftware\Microsoft\Windows\CurrentVersion\Run

打开注册表方法: win + R ,运行regedit,按照上面路径点到Run上,右侧的值就是开机启动项。

确认开机自启动设置成功方法: win + R , 运行 msconfig,点开启动项,前面有对号的就是开机的启动项。

写入注册表:

var regedit = require('regedit'); //引入regedit
regedit.putValue({
    'HKCU\Software\Microsoft\Windows\CurrentVersion\Run':{
        'vanish2' : {
            value : "C:Windows",
            type : 'REG_SZ'   //type值为REG_DEFAULT时,不会自动创建新的name
        }
    }
},function(err){
console.log(err);
})

列出regedit列表:

regedit.list('HKCU\Software\Microsoft\Windows\CurrentVersion\Run',function(err,result){
    console.log(result);
  })

创建Key值,这个key值,其实就是注册表里的项值,新建项值(一个文件夹,不是文件夹里的值)。

regedit.createKey('HKCU\Software\Microsoft\Windows\CurrentVersion\Run\ele', function(err) {
     console.log(err);
  })

删除Key值,会删除文件夹下所有值

regedit.deleteKey('HKCU\Software\Microsoft\Windows\CurrentVersion\Run', function(err) {
     console.log(err);
  })

删除值,regedit的文档中并没看到这一项,寻找到的文档中,给出了一个凑合着的方案就是清空键值,利用putValue,给原来Name的值变为空

代码示例:

regedit.putValue({
    'HKCU\Software\Microsoft\Windows\CurrentVersion\Run':{
      'vanish2' : {
        value : "",
        type : 'REG_SZ'
      }
    }
  },function(err){
    console.log(err);
  })

删除参照原github地址:https://github.com/ironSource/node-regedit#regeditdeletekeystringarray-function

当然这种方式治标不治本,所以想要真正的去删除一个键值,还需要靠其他的东西(或许regedit 有,只是我没看到。)

新的删除方法,需要引用 child_process

示例代码:

var cp = require('child_process');
//删除vanish2的键值
cp.exec("REG DELETE HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v vanish2 /f",function(err)
{
  console.log(err);
});

这种child_process 也可以去添加注册表,原理是用系统的reg功能,想要查看Reg功能,请在cmd中,运行 REG /?,会得到提示,同时这些在cmd之中,可以直接运行,所以可以先在cmd运行成功后,再放入程序中调试。

REG 操作查询:

REG QUERY /?
REG ADD /?
REG DELETE /?
REG COPY /?
REG SAVE /?
REG RESTORE /?
REG LOAD /?
REG UNLOAD /?
REG COMPARE /?
REG EXPORT /?
REG IMPORT /?
REG FLAGS /?

所以通过child_process就可以上面的命令了:

var cp = require('child_process');
cp.exec("REG QUERY HKCU\Software\Microsoft\Windows\CurrentVersion\Run",function(error,stdout,stderr) {
console.log(error);
  console.log(stdout);
  console.log(stderr);
});

 希望对你有帮助,谢谢。

原文地址:https://www.cnblogs.com/lhwblog/p/7732245.html