05.《Electron 跨平台开发实战》- chapter05-创建多窗口应用

项目代码

https://github.com/electron-in-action/firesale/tree/chapter-5

代码解析

重构打开文件函数

添加参数, targetWindow 表示当前窗口
main.js

const openFile = exports.openFile = (targetWindow, file) => {
    const content = fs.readFileSync(file).toString();
    targetWindow.webContents.send('file-opened', file, content); 
};

renderer.js
在渲染进程中,使用 remote.getCurrentWindow(); 获取当前窗口

const { remote, ipcRenderer } = require('electron');
const mainProcess = remote.require('./main.js');
const currentWindow = remote.getCurrentWindow();
mainProcess.openFile(currentWindow );

window的坐标

const currentWindow = BrowserWindow.getFocusedWindow();
currentWindow.getPosition()

    const { app, BrowserWindow, dialog } = require('electron');
    ...
    const currentWindow = BrowserWindow.getFocusedWindow();
    if (currentWindow) {
        const [currentWindowX, currentWindowY] = currentWindow.getPosition();
        x = currentWindowX + 10;
        y = currentWindowY + 10;
    }

与macOS集成

在 macOS 系统中,许多应用即使关闭所有系统,也仍然可以在后台保存运行。
而 默认情况下 electron 会触发window-all-closed事件退出应用
如果单击Dock区域的图标,激活activate事件,再次打开应用窗口

所以,检测是否是macOS系统,修改该行为:

//所有窗口关闭
app.on('window-all-closed', ()=>{
    //检测应用是否运行在 macOS系统中
   if (process.platform === 'darwin'){
       return false; //返回false,取消默认行为
   }

   app.quit();
});

//只用macOS系统才会触发`activate`事件
app.on('activate', (event, hasVisibleWindows)=>{
    if(!hasVisibleWindows){
        createwindow();
    }
});


其中,

process

   是Node 提供,无须特意引入即可在任何地方使用

process.platform

   是当前所处的平台名称:
   - darwin:macOS系统
   - freebsd:
   - linux:
   - sunos:
   - win32: window 系统
原文地址:https://www.cnblogs.com/easy5weikai/p/13098676.html