Monkeyonawall
Monkeyonawall

Reputation: 137

Electron Browser Window Prevent Control+W closing window

I have an electron js app with Angular 8. If the user performs the command control+w, it automatically closes the window. I try looking through the BrowserWindow Api, however, I couldn't find a flag or handler to prevent this behavior from happening.

Upvotes: 2

Views: 2996

Answers (3)

Luciano
Luciano

Reputation: 21

For whom it may concern, another solution can be:

app.on("ready", () => {
  app.on("browser-window-focus", () => {
    globalShortcut.registerAll(
      ["CommandOrControl+R"],
      () => {
        return;
      }
    );
  });
  app.on("browser-window-blur", () => {
    globalShortcut.unregisterAll();
  });
});

This way we prevent from blocking globalShortcuts in other applications. More info about electron accelerators: https://www.electronjs.org/docs/api/accelerator

Upvotes: 1

avisk
avisk

Reputation: 390

Removing the default application menu removes other useful shortcuts, so I would suggest specifically targeting Ctrl + W, which can be done using globalShortcut:

const { app, globalShortcut } = require("electron");

app.on("ready", () => {
    globalShortcut.register("CommandOrControl+W", () => {
        //stuff here
    });
});

More info on this here

Upvotes: 2

aabuhijleh
aabuhijleh

Reputation: 2464

You need to change or remove the default application menu which has this shortcut Window -> Close Ctrl+W by default

Menu.setApplicationMenu(null) // remove default application menu

// or

browserWindow.setMenu(null) // just remove default menu of a specific window and not all windows

This should do the trick

Relevant docs:

Upvotes: 8

Related Questions