Electron開發實戰之記帳軟件10——保證只有一個實例

代碼倉庫: https://github.com/hilanmiao/LanMiaoDesktophtml

若是咱們不進行任何設置的話,那麼咱們的程序就會出現多個實例的狀況,以下圖。git

蘇南大叔也寫過一篇文章,介紹了兩種方式。有興趣的能夠看一下。 https://newsn.net/say/electron-single-instance-lock.htmlgithub

咱們用包都是最新的,因此直接用Electron4 自帶的方式,解決單實例問題便可。app

核心代碼:electron

const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 當運行第二個實例時,將會聚焦到myWindow這個窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })

  // 建立 myWindow, 加載應用的其他部分, etc...
  app.on('ready', () => {
     createWindow()
  })
}

你還能夠經過app.hasSingleInstanceLock()判斷是否有單一鎖,經過app.releaseSingleInstanceLock()釋放全部的鎖,並容許多實例再次運行。ui

相關文章
相關標籤/搜索