【问题标题】:How to disable the system context menu in Electron custom titlebar?如何禁用电子自定义标题栏中的系统上下文菜单?
【发布时间】:2021-04-24 23:25:39
【问题描述】:

我正在使用带有自定义标题栏的 Electron 无框窗口,但是右键单击它时会出现一个上下文菜单。如何禁用显示此菜单?

这是电子版:

"electron": "^11.3.0",

这是电子启动程序:main.js,但是应用启动后系统上下文菜单在这里不起作用。

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const url = require('url');

let mainWindow;
function createWindow() {
  mainWindow = new BrowserWindow({
    show: false,
    frame: false,
    useContentSize: true,
    hasShadow: true,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true,
      contextIsolation: false,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  mainWindow.loadURL(
    process.env.NODE_ENV === 'development'
      ? 'http://localhost:5000'
      : url.format({
          pathname: path.join(__dirname, '../build/index.html'),
          protocol: 'file:',
          slashes: true,
        })
  );

  if (process.env.NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools();
  }

  mainWindow.on('system-context-menu', (event, _point) => {
    event.preventDefault();
  });
}

const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      mainWindow.focus();
    }
  });

  app.whenReady().then(createWindow);

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

  // just work in macOS
  // https://www.electronjs.org/docs/api/app#%E4%BA%8B%E4%BB%B6-activate-macos
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
}


【问题讨论】:

    标签: electron


    【解决方案1】:

    在Windows上,你应该可以拦截BrowserWindowsystem-context-menu事件并取消它。

    mainWindow.on("system-context-menu", (event, _point) => {
        event.preventDefault();
    });
    

    此行为是在 this PR 的 Electron 11 中添加的。

    编辑:由于this Electron bug,该事件实际上不会针对无框窗口触发。在我的解决方案起作用之前,它需要修复。我不知道有任何解决方法。

    【讨论】:

    • 您使用的是哪个 Electron 版本?你能显示一些代码吗?
    • 感谢您的回复,我在上面的问题中添加了我的代码
    • 哎呀 - 由于Electron bug,事件实际上并没有触发。在我的解决方案起作用之前需要修复它......
    • 据我所知,没有。 FWIW 这只是无框窗户的问题。但是您始终可以禁用使窗口无法关闭/最小化/等的项目
    • 还是谢谢大家,我可能会等这个Electron bug以后解决。
    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    相关资源
    最近更新 更多