2019-04-27蘇南大叔electron/nwjs如何加入開機啓動項? 恰好發佈了這麼一篇文章,用的庫是node-auto-launch,不過由於我暫時先不試了,等叔叔後續文章更新再試吧,這個庫支持windows、mac、linux。而咱們的node-winreg只支持windows。vue
npm install winreg -save
node
// 引用winreg模塊 var WinReg = require('winreg') var startOnBoot = { // 設置自動啓動 enableAutoStart: function (name, file, callback) { var key = getKey() key.set(name, WinReg.REG_SZ, file, callback || noop) }, // 取消自動啓動 disableAutoStart: function (name, callback) { var key = getKey() key.remove(name, callback || noop) }, // 獲取是否自動啓動 getAutoStartValue: function (name, callback) { var key = getKey() key.get(name, function (error, result) { if (result) { callback(null, result.value) } else { callback(error) } }) } } var RUN_LOCATION = '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' // 獲取註冊表key function getKey() { return new WinReg({ hive: WinReg.HKCU, // CurrentUser, key: RUN_LOCATION }) } // callback自定義方法,你能夠在這裏寫代碼 function noop() { } // 導出 module.exports = startOnBoot
我是單首創建了一個js文件,而後在index.js中引入便可,以下圖。linux
咱們確定有個頁面手動設置開關機了,我在Settings.vue文件中寫好了。通訊是用的ipc,因此主進程也要寫相應的代碼。須要注意的是首次不要watch autoStart這個對象,否則後屢次調用相關事件。git
渲染進程核心代碼:github
mounted() { this.getAutoStartValue() }, methods: { changeAutoStart() { if (this.autoStart) { this.enableAutoStart() } else { this.disableAutoStart() } }, getAutoStartValue() { // 檢查是否自動啓動 ipcRenderer.send('getAutoStartValue') ipcRenderer.on('getAutoStartValue', (event, result) => { this.autoStart = result // 首次不watch對象 this.$watch('autoStart', this.changeAutoStart) }) }, enableAutoStart() { // 設置自動啓動 ipcRenderer.send('enableAutoStart') }, disableAutoStart() { // 取消自動啓動 ipcRenderer.send('disableAutoStart') }, }
主進程核心代碼:web
/** * 開機啓動 */ function ipcStartOnBoot() { // 檢查是否自動啓動 ipcMain.on('getAutoStartValue', () => { startOnBoot.getAutoStartValue(ApplicationName, (error, result) => { if (error) { mainWindow.webContents.send('getAutoStartValue', false) } else { mainWindow.webContents.send('getAutoStartValue', true) } }) }) // 設置開機自動啓動 ipcMain.on('enableAutoStart', () => { startOnBoot.enableAutoStart(ApplicationName, process.execPath) }) // 取消開機自動啓動 ipcMain.on('disableAutoStart', () => { startOnBoot.disableAutoStart(ApplicationName) }) }
代碼不必定所有都要放在主進程main的index文件中,例如這個開關機所有放到渲染進程裏的uitls這種工具類裏,須要的時候再調用也是能夠的。npm
開發模式很差測試,咱們build以後安裝咱們的程序,能夠看到註冊表和任務管理器都能看到咱們的程序是啓用狀態(真尷尬,只有家裏的電腦一直是已禁用狀態XD。公司電腦,筆記本,win七、win10都是能夠的。難道要設置多個註冊表,或是要取得特殊權限,仍是說被某個軟件禁止了?)。json
2019-04-26 bug 修復: 發現已管理員身份運行,而後設置開機啓動到HKLM註冊表是能夠的。打包的不行,必須安裝的。並且打包的時候要在package.json的build參數設置申請管理員權限。因此說,我本地電腦寫入HKCU不行,而公司電腦是能夠的,大機率的緣由就是權限和登陸帳戶的問題。windows
"win": { "icon": "build/icons/icon.ico", "requestedExecutionLevel": "highestAvailable" },
若是是公司產品那麼推薦購買簽名證書,我的的就不必了,畢竟一年要幾百刀。下面是簽名和不簽名的區別,windows下沒那麼嚴格,可是mac必需要簽名,不然沒法放到App Store上。