Electron自定义关闭按钮

2020-07-07  本文已影响0人  子夜照弦歌

原创文章,转载请注明出处

应用场景:项目全屏最大化,需要自定义一个菜单栏

  1. 创建页面
  2. 渲染进程发送指令
  3. 主进程关闭
    代码如下:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="renderer" content="webkit">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link rel="icon" href="<%= BASE_URL %>favicon.ico">
  <title><%= webpackConfig.name %></title>
  <style>
    html,
    body {
      font-family: PingFanXgSC-Regular;
      position: relative;
    }

    #menu {
      width: 100vw;
      height: 28px;
      position: absolute;
      right: 0;
      top: 0;
    }

    #close {
      background: #ff0000;
      width: 42px;
      height: 28px;
      line-height: 28px;
      color: #fff;
      text-align: center;
      font-size: 18px;
      float: right;
      visibility: hidden;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div id="app"></div>
  <div id="menu">
    <div id="close">x</div>
  </div>
  <script>
    let menu = document.getElementById('menu');
    let close = document.getElementById('close');
    menu.onmouseover = function () {
      close.style.visibility = 'visible';
    }
    menu.onmouseout = function () {
      close.style.visibility = 'hidden';
    }
    close.onclick = function () {
      try {
        var ipcRender = require('electron').ipcRenderer
        ipcRender.send('handelClose', "执行关闭")
      }
      catch (e) {
        console.log("不支持ipcRenderer")
      }
      // alert("点击关闭")
    }
  </script>
</body>
</html>
const { app, BrowserWindow, Menu, ipcMain } = require('electron')
const win = null;
function createWindow() {
  Menu.setApplicationMenu(null)
  // 创建浏览器窗口
  win = new BrowserWindow({
    // width: 800,
    // height: 600,
    fullscreen: true,
    webPreferences: {
      nodeIntegration: true
    },
    // autoHideMenuBar: true,

    // titleBarStyle: 'customButtonsOnHover', 
    // frame: false
  })
  // 并且为你的应用加载index.html
  win.loadFile('./html/index.html')
  // 打开开发者工具
  // win.webContents.openDevTools()
}

// Electron会在初始化完成并且准备好创建浏览器窗口时调用这个方法
// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(createWindow)
//当所有窗口都被关闭后退出
app.on('window-all-closed', () => {
  // 在 macOS 上,除非用户用 Cmd + Q 确定地退出,
  // 否则绝大部分应用及其菜单栏会保持激活。
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
app.on('activate', () => {
  // 在macOS上,当单击dock图标并且没有其他窗口打开时,
  // 通常在应用程序中重新创建一个窗口。
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})
// 执行关闭 自定义关闭
ipcMain.on('handelClose', function (res) {
  console.log("执行关闭操作")
  app.quit()
})
// 您可以把应用程序其他的流程写在在此文件中
// 代码 也可以拆分成几个文件,然后用 require 导入。
上一篇 下一篇

猜你喜欢

热点阅读