Electronic + Vue custom Click to maximize, minimize and close window events

Posted by ianhull on Fri, 04 Mar 2022 08:50:26 +0100

First, let's briefly understand the process types of Electron - rendering process and main process

Main process: Electron runs package JSON's main script process.
Rendering process: a process that runs on a web page.
An Electron application has and has only one main process.
The script running in the main process presents the user interface by creating a web page. The web page in each Electron runs in its own rendering process.
The main process manages all web pages and their corresponding rendering processes. Each rendering process is independent, and it only cares about the web page it runs.
The main process and the rendering process can communicate with each other. If the ipcRenderer and ipcMain modules can be used to send messages, the remote module can be used for RPC (remote procedure call) communication.
In my Vue electron demo project, package The main script of JSON is background js:

 
 

1, Using the remote module, the main process and rendering process communicate;

Directly adjust the function in the rendering process:

be careful:

Element and sass are installed in the project
Using the remote module, the main process module is used in the rendering process. Using the remote module, you can call the method of the main process object without explicitly sending inter process messages. Specific usage reference: Official website
remote.getCurrentWindow() returns BrowserWindow - the window to which this web page belongs. It is the same as the win of the main process, that is, the new BrowserWindow ({....}) in the main process

header.vue file:

<template>
  <div class="header">
   	<span class="el-icon-minus" @click="minimizeWin"></span>
    <span class="el-icon-full-screen" @click="maximizeWin"></span>
    <span class="el-icon-close" @click="closeWin"></span>
   </div>
</template>
<script>
import { remote } from 'electron';
export default {
  methods: {
       minimizeWin(){
      remote.getCurrentWindow().minimize(); // window minimizing
    },
    maximizeWin(){
      const win=remote.getCurrentWindow();
      if(win.isMaximized()){ // Determine whether the window has been maximized 
        win.restore();// Restore original window size
      }else{
         win.maximize();  //maximize window
      }
    },
    closeWin(){
      remote.getCurrentWindow().close(); // Closing the window also ends all processes
    }
  }
}
</script>
<style lang="scss">
	.header{
		span{
			font-size:20px;
			margin-right:20px;
			color:red;
		}
	}
</style>

The icon effect is as follows (at this time, it has the functions of minimizing, maximizing, restoring and closing the current window):
 

2, Use the ipcRenderer # and # ipcMain modules to send messages to let the main process and rendering process communicate;

Send a message to the main process in the rendering process to inform the main process of what I want to do
be careful:

  1. Send information to the main process through ipcRender module in the rendering process;
  2. The main process receives the message of the rendering process and calls the function to perform the corresponding operation.

 

<template>
  <div class="header">
   	<span class="el-icon-minus" @click="minimizeWin"></span>
    <span class="el-icon-full-screen" @click="maximizeWin"></span>
    <span class="el-icon-close" @click="closeWin"></span>
   </div>
</template>
<script>
const ipcRenderer = require('electron').ipcRenderer;
export default {
  methods: {
     minimizeWin(){
       ipcRenderer.send('window-min') // Notify the main process that I want to minimize the window
    },
    maximizeWin(){
      ipcRenderer.send('window-max')
    },
    closeWin(){
      ipcRenderer.send('window-close')
    }
  }
}
</script>
<style lang="scss">
	.header{
		span{
			font-size:20px;
			margin-right:20px;
			color:red;
		}
	}
</style>

In background JS file: add the following code:

async function createWindow() {
  createMenu();
  // Create the browser window.
  win = new BrowserWindow({
    width: 1300,
    height: 660,
    minWidth: 1300,
    useContentSize: true,
    resizable: true,
    frame: false,//You can hide the border of the window by setting the value of frame to false.
    //  backgroundColor: '#DC143C',
    // titleBarStyle: 'hidden',
    webPreferences: {
      webSecurity: false, //Remove cross domain restrictions
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      // eslint-disable-next-line no-undef
      preload: `${__static}/preload.js`
    },
    //${__ Static} corresponds to the public directory
    // eslint-disable-next-line no-undef
    icon: `${__static}/img/icons/logo-64.png`
    // icon: `${__static}/img/icons/favicon.ico`
  });
  if (process.platform === 'darwin') {
    // eslint-disable-next-line no-undef
    app.dock.setIcon(`${__static}/img/icons/logo-512.png`);
  }
  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');
    //Detect version updates
    // updateHandle(win, feedUrl);
  }
  win.on('closed', () => {
    win = null;
  });
  globalShortcut.register('CommandOrControl+Shift+i', function () {
    win.webContents.openDevTools();
  });
  // esc,
  globalShortcut.register('ESC', function () {
    win.unmaximize();
  });
  //  Add three pieces 1, 2 and 3; Win is win = new BrowserWindow({...}) Yes.

// 1. Window minimization
ipcMain.on('window-min',function(){ // Receive the notification of the window minimization operation of the rendering process, and call the window minimization function to execute the operation
  win.minimize();
})

// 2. Window maximization and recovery
ipcMain.on('window-max',function () {
  if(win.isMaximized()){ // true indicates that the window has been maximized
    win.restore();// Restores the window to its previous state
  }else{
    win.maximize();
  }
})

// 3. Close the window
ipcMain.on('window-close',function (){
  win.close();
})
}

be careful:

The version of electron I use is 11.2.1, which is introduced in the rendering process

const ipcRenderer = require('electron').ipcRenderer;

An error will appear:

The solution is in the root directory Vue config. JS file:

module.exports = {
    pluginOptions: {
        electronBuilder: {
            nodeIntegration: true
        }
    }
}

Can solve this problem.

Finally, the electron ic borderless configuration is attached:

No border window implementation

You can hide the border of the window by setting the value of frame to false.

win = new BrowserWindow({
    frame: false,
  });
Traffic lights on mac
After the implementation of borderless, the traffic lights can be kept on the mac by setting the titleBarStyle property. The value of titleBarStyle is optional:

Default: default, standard gray opaque mac title bar;

hidden: full size content window, with standard control buttons reserved;

hiddenInset: the control button is larger from the border;

customButtonsOnHover: displayed when the mouse crosses the upper left corner (the official document shows that this attribute is in the experiment);

win = new BrowserWindow({
    frame: false,
    titleBarStyle: 'hidden',
  });
Window can be dragged
Set the style at the position to be dragged - WebKit app region: drag; You can drag. (it is mentioned in the official document that the drag attribute will affect the click event, so it is necessary to set no drag in the click area, but try not to set no drag on the mac. Double clicking seems to be no problem, and the reason is unknown).

-webkit-app-region: drag;
Note: setting the drag property affects the developer tool. If the developer tool and application are displayed in the same window, the window cannot be dragged. At this time, it is best to let the developer tool display independently. Reference article: [electron] - some pits in the application of borderless window
 

Topics: Vue Electron