Подтвердить что ты не робот

Как поймать событие нажатия кнопки закрытия окна приложения в приложении "Электрон"

Я хочу поймать событие нажатия кнопки закрытия окна приложения в приложении Electron.

Я пытаюсь разработать приложение Electron для Mac OSX. Я хочу скрыть окно приложения, а не прерывать приложение, когда пользователь нажимает кнопку закрытия окна, как и другие приложения Mac.

Однако я не могу обнаружить, что система должна быть завершена или она должна быть скрыта, потому что в любом случае событие close browser-window вызывается при нажатии кнопки закрытия, OS выключается или приложение завершается командой quit, Cmd+Q.

Есть ли способ поймать событие нажатия кнопки закрытия окна приложения в приложении Electron?

Благодарим вас за помощь.


Postscript

Чтобы обнаружить событие нажатия кнопки закрытия, я пробовал этот код

var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require('menu');

var force_quit = false;

var menu = Menu.buildFromTemplate([
  {
    label: 'Sample',
    submenu: [
      {label: 'About App', selector: 'orderFrontStandardAboutPanel:'},
      {label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: function() {force_quit=true; app.quit();}}
    ]
  }]);

app.on('window-all-closed', function(){
    if(process.platform != 'darwin')
        app.quit();
});

app.on('ready', function(){

    Menu.setApplicationMenu(menu);

    mainWindow = new BrowserWindow({width:800, height:600});

    mainWindow.on('close', function(e){
        if(!force_quit){
            e.preventDefault();
            mainWindow.hide();
        }
    });

    mainWindow.on('closed', function(){
        console.log("closed");
        mainWindow = null;
        app.quit();
    });

    app.on('activate-with-no-open-windows', function(){
        mainWindow.show();
    });
});

С помощью этого кода приложение скрывается при нажатии кнопки закрытия окна приложения, и приложение заканчивается при вводе Cmd+Q. Однако, когда я пытаюсь отключить ОС, событие завершения работы предотвращается.

4b9b3361

Ответ 1

Вы можете поймать его, используя событие close browser-window api. Вы можете попробовать следующее, чтобы проверить это...

var app = require('app');

var force_quit = false;

app.on('ready', function () {        
    mainWindow = new BrowserWindow({ width: 800, height: 600 });

    mainWindow.on('close', function() { //   <---- Catch close event

        // The dialog box below will open, instead of your app closing.
        require('dialog').showMessageBox({
            message: "Close button has been pressed!",
            buttons: ["OK"]
        });
    });
});

Обновление:

Чтобы разделить функциональность, вы можете сделать следующее...

var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require('menu');

var force_quit = false;
var menu = Menu.buildFromTemplate([
{
    label: 'Sample',
    submenu: [
        {label: 'About App', selector: 'orderFrontStandardAboutPanel:'},
        {
            label: 'Quit', 
            accelerator: 'CmdOrCtrl+Q', 
            click: function() { 
                force_quit=true; app.quit();
            }
        }
    ]
}]);

app.on('window-all-closed', function(){
    if(process.platform != 'darwin')
        app.quit();
});

app.on('ready', function(){

    Menu.setApplicationMenu(menu);

    mainWindow = new BrowserWindow({width:800, height:600});

    // Continue to handle mainWindow "close" event here
    mainWindow.on('close', function(e){
        if(!force_quit){
            e.preventDefault();
            mainWindow.hide();
        }
    });

    // You can use 'before-quit' instead of (or with) the close event
    app.on('before-quit', function (e) {
        // Handle menu-item or keyboard shortcut quit here
        if(!force_quit){
            e.preventDefault();
            mainWindow.hide();
        }
    });

    // Remove mainWindow.on('closed'), as it is redundant

    app.on('activate-with-no-open-windows', function(){
        mainWindow.show();
    });
});

// This is another place to handle events after all windows are closed
app.on('will-quit', function () {
    // This is a good place to add tests insuring the app is still
    // responsive and all windows are closed.
    console.log("will-quit");
    mainWindow = null;
});

В приведенном выше коде используется before-quit обработчик событий для обработки событий приложения "закрыть" в приложении api. События браузера "закрыть" по-прежнему обрабатываются в окне браузера api на mainWindow.on('close').

Кроме того, событие will-quit - лучшее место для тестирования проблем до того, как приложение полностью закрывается.

Ответ 2

app.on('ready', ()=> {
let win = new BrowserWindow({width:800, height:600}) 
win.loadURL('file://'+__dirname+'/index.html')
win.on('closed', () => {
    console.log(' ---- Bye Bye Electron ---- ')
  });
})

Таким образом, вы можете поймать закрытое событие