electron- 项目开发 (1)

671 阅读3分钟

开发界面效果如下: image.png

本次项目为了 体验下 ant-design-vue UI ,所以使用的 ant 作为样式框架。

(一)界面按照 即使设计上面的 UI 图进行了还原,这里就不再进行过多说明了,喜欢的友友可自行设计一个登录界面。

(二)本次的技术点在 登录界面 上面 40px的可拖拽区域,以及右上角 最小化和关闭 程序 按钮功能的实现。

可拖拽区域实现思路: 通过 css 代码,-webkit-app-region: drag;这个可拖拽属性,直接搞定可拖拽区域,需要被拖拽的盒子,设置这个 css 代码即可,同时,这个css 代码会导致盒子中的其他子元素,无法被点击,因此,对其他需要实现功能或者效果的子元素,需要设置 css 的这个属性 -webkit-app-region: no-drag;通过属性 -webkit-app-region的配合,来实现拖拽功能。

实例: 还记得 electron 本身自带一个可以拖拽的区域,以及最小化、关闭程序、窗口还原 这三个常见的功能按钮。

image.png

这里如果使用自定义去调整成我们想要的样子,有点麻烦,所以就搞成自定义的拖拽区域和功能按钮。

(1)隐藏 electron 自带的边框

关键代码:frame: false

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 1220,
    height: 680,
    frame: false, //隐藏自带拖拽区域
    resizable: false,
    // titleBarStyle: 'hidden', 
    autoHideMenuBar: true,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: true,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      preload: path.join(__dirname, "preload.js"),
    },/*  */
  });

(2)在代码中设置一个可以拖拽的区域,本次项目将登录页顶部的 40px 区域作为一个可拖拽区域,即一个自定义的 Vue 组件。

对整个 drag-bar 区域设置 css -webkit-app-region: drag; 对两个功能按钮 设置css -webkit-app-region: no-drag;

<template>
    <div class="drag-bar">
        <!-- 缩小 -->
        <a-icon type="minus" class="icon icon-minus" @click="shinkClick"/>
        <!-- 关闭 -->
        <a-icon type="close" class="icon icon-close" @click="quitExeClick"/>
    </div>
</template>
<script>
export default {
    name:'dragBar',
    data(){
        return {
            mainWindow:null
        }
    },
    created(){
        this.mainWindow = window.electron
    },
    methods:{
        shinkClick(){
            this.mainWindow.minimize()
        },
        quitExeClick(){
            this.mainWindow.quitApp()
        }
    }
}
</script>
<style lang="scss" scoped>
.drag-bar{
    height:40px;
    width: 100%;
    position: absolute;
    z-index: 3;
    -webkit-app-region: drag; //设置可以拖拽的区域
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .icon{
        -webkit-app-region: no-drag;
        padding: 0 16px;
    }
}
</style>

(3)最大化和最小化按钮的实现

利用了 ipcMain 进行通信。

从上节讲到的 preload.js 暴露的 electron Api ,通过 electron Api ,实现功能按钮。

preload.js 文件。


// 从 electron 中引入  contextBridge,ipcRenderer
const { contextBridge, ipcRenderer } = require("electron");

contextBridge.exposeInMainWorld("electron", {
  contextBridge,
  ipcRenderer,
  quitApp: () => ipcRenderer.invoke("quit-app"), //退出程序
  minimize:()=> ipcRenderer.invoke("minimize"), //最小化
});

主进程文件添加这两个监听事件 quit-app,minimize,利用 BrowserWindow 最小化窗口事件进行功能实现。BrowserWindow.getFocusedWindow().minimize()

quit-app 中,为什么使用 app.exit();,而不像代码中使用 app.quit,是因为,在有些情况下,quit 并不能直接将窗口关闭,比如,你打开了多个窗口,需要将其他的窗口先退出,才能关闭,而 exit 可以强制关闭。

主进程文件:

"use strict";

import { app, protocol, BrowserWindow, ipcMain } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
const path = require("path"); //引入path
// import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer";
const isDevelopment = process.env.NODE_ENV !== "production";

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 1220,
    height: 680,
    frame: false,
    resizable:false,
    // titleBarStyle: 'hidden', 
    autoHideMenuBar:true,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: true,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      preload: path.join(__dirname, "preload.js"),
    },
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    win.loadURL("app://./index.html");
  }
}

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      // await installExtension(VUEJS_DEVTOOLS);
    } catch (e) {
      console.error("Vue Devtools failed to install:", e.toString());
    }
  }
  createWindow();
});

// 引入  ipcMain,同时添加监听函数,与 preload.js 中的 quitApp 对应
ipcMain.handle("quit-app", () => {
  app.exit();
});
ipcMain.handle("minimize", () => {
  BrowserWindow.getFocusedWindow().minimize()
});


// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", (data) => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}


本次主界面的登录开发,就算完成了。

★,°:.☆( ̄▽ ̄)/$:.°★