微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Electron 自定义标题栏中禁用系统上下文菜单?

如何解决如何在 Electron 自定义标题栏中禁用系统上下文菜单?

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

enter image description here

这是电子版:

"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',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();
    }
  });
}


解决方法

在 Windows 上,您应该能够拦截 BrowserWindowsystem-context-menu 事件并取消它。

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。