2016-03-10 38 views
7

我不知道這是否可能,但我不妨給它一個機會並提出要求。 我正在做一個電子應用程序,我想知道是否有可能一次只有一個實例。如何防止Electron中的多個實例

我找到了這個gist,但我不確定使用它很熱。有人可以分享一些更好的想法嗎?

var preventMultipleInstances = function(window) { 
    var socket = (process.platform === 'win32') ? '\\\\.\\pipe\\myapp-sock' : path.join(os.tmpdir(), 'myapp.sock'); 
    net.connect({path: socket}, function() { 
     var errorMessage = 'Another instance of ' + pjson.productName + ' is already running. Only one instance of the app can be open at a time.' 
     dialog.showMessageBox(window, {'type': 'error', message: errorMessage, buttons: ['OK']}, function() { 
      window.destroy() 
     }) 
    }).on('error', function (err) { 
     if (process.platform !== 'win32') { 
      // try to unlink older socket if it exists, if it doesn't, 
      // ignore ENOENT errors 
      try { 
       fs.unlinkSync(socket); 
      } catch (e) { 
       if (e.code !== 'ENOENT') { 
        throw e; 
       } 
      } 
     } 
     net.createServer(function (connection) {}).listen(socket);; 
    }); 
} 

回答

13

使用makeSingleInstance功能app模塊中,甚至還有在文檔的例子。

+0

哇,我感到啞巴。我從未在他們的API中看到過。我從這裏閱讀[http://electron.atom.io/docs/v0.36.8/](http://electron.atom.io/docs/v0.36.8/) – Eduard

0

如果您需要代碼。

let mainWindow = null; 
//to make singleton instance 
const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => { 
    // Someone tried to run a second instance, we should focus our window. 
    if (mainWindow) { 
     if (mainWindow.isMinimized()) mainWindow.restore() 
     mainWindow.focus() 
    } 
}) 

if (isSecondInstance) { 
    app.quit() 
} 
相關問題