[Electron]第一个自定义窗口

Electron窗口

第一个自定义窗口

要求

  • 加载一个自己定义的窗口

  • 界面上定义一个最大化按钮和还原按钮,用来控制窗口最大化和还原

步骤

1. 编写html,编写页面
<!DOCTYPE html>
<html>
​
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
​
<body>
    <h1>我们自己的Electron窗口!</h1>
    <!-- 1. html中编写 
            1.1 添加当前窗口大小状态
            1.2 添加最大化窗口按钮和还原按钮
    -->
    <p>当前窗口大小: <strong id="state">最初状态</strong></p>
    <button id="btnMax">最大化窗口</button>
    <button id="btnReduct">还原</button>
    <!-- 加载js -->
    <script src="index.js"></script>
</body>
</html>
2. 编写index.js

点击最大化按钮时调用自定义方法 window.btn.btnIsMax()点击还原按钮时调用自定义方法 window.btn.btnReduct()

// 2. js文件中写
// 2.1 获取最大化按钮和还原按钮
// 2.2 点击时分别调用 window.btn.btnMax()方法 和window.btn.btnReduct()方法
var btnMax = document.getElementById("btnMax");
​
btnMax.addEventListener('click',async ()=>{
    const btnIsMax = await window.btn.btnIsMax();
    console.log(btnIsMax);
    document.getElementById("state").innerHTML = btnIsMax?"最大化":"正常";
})
​
var btnReduct = document.getElementById("btnReduct");
btnReduct.addEventListener('click',async ()=>{
    await window.btn.btnReduct();
    document.getElementById("state").innerHTML = "最初状态";
})
3. 创建preload.js

通过contextBridge 在窗口挂载window.btn.btnMax()方法 和window.btn.btnReduct()方法通过ipcipcRenderer 调用主线程方法

const {contextBridge,ipcRenderer } = require('electron/renderer')
contextBridge.exposeInMainWorld('btn',{
    btnIsMax : ()=>ipcRenderer.invoke('winSize:btnIsMax'),
    btnReduct : ()=>ipcRenderer.invoke('winSize:btnReduct')
})   
4. 修改main.js

用ipcMain监听渲染进程中window.btn.btnMax()方法 和window.btn.btnReduct()方法

const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('node:path')
​
const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })
​
  win.loadFile('index.html')
​
  // 监听winSize:btnIsMax
  ipcMain.handle('winSize:btnIsMax', () => {
    this.flag = win.isMaximized()
    if (this.flag ) {
      win.unmaximize()
    } else {
      win.maximize()
    }
    return  !this.flag
  })
​
  // 监听winSize:btnReduct
  ipcMain.handle('winSize:btnReduct', () => {
    if (win.isMaximized()) {
      win.unmaximize()
    }
  })
}
​
app.whenReady().then(() => {
  createWindow()
​
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})
​
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
5. 界面效果

  • 22
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值