通过函数调整 electron window 的大小

Resize electron window through function

几天来我一直在努力寻找这个问题的答案,但似乎找不到好的解决方案。

我是 Eelectron 的新手,但我正在尝试创建一个应用程序,我可以在事件发生后调用一个函数,然后调整 window.

的大小

到目前为止我所看到的,我必须使用 icpMain 和 icpRender,但是每当我尝试执行建议的代码时,我要么在我的脚本中加载有问题,要么得到一个“未定义”错误.

main.js:

const electron  = require('electron');
const {ipcMain} = require('electron');
const url       = require('url');
const path      = require('path');
const {app, BrowserWindow} = electron;
let mainWindow;
app.on('ready',function(){
    mainWindow = new BrowserWindow({
        transparent:    true,
        frame:          false,
        width:          500,
        height:         500,
        webPreferences: {
            preload: path.join(__dirname,'js/login.js')
        }
    });
    //mainWindow.removeMenu();
    mainWindow.loadURL(url.format({
        pathname:   path.join(__dirname,'html/login.html'),
        protocol:   'file:',
        slashes:    true
    }))
    ipcMain.on('resize-me-please', (event, arg) => {
        mainWindow.setSize(300,300)
    })
});

终于想通了

在您的 main.js 中确保您在应用程序对象中设置以下内容:

webPreferences: {
    nodeIntegration: true,
    contextIsolation: false,
    enableRemoteModule: true,
}

完整示例:

const electron  = require('electron');
const url       = require('url');
const path      = require('path');
const {app, BrowserWindow} = electron;
let mainWindow;
app.on('ready',function(){
    mainWindow = new BrowserWindow({
        transparent:    true,
        frame:          false,
        width:          500,
        height:         500,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
        }
    });
    //mainWindow.removeMenu();
    mainWindow.loadURL(url.format({
        pathname:   path.join(__dirname,'html/login.html'),
        protocol:   'file:',
        slashes:    true
    }))
});

然后,如果您使用像 jquery 和 jquery-UI 这样的库,请确保使用以下命令安装它:

  • npm 安装jquery --保存
  • npm 安装jquery-ui --保存

然后在您的 index.html 中,您需要请求 ui 重新 jquery,这也可以通过文件通过以下命令完成:

<script>window.$ = window.jQuery = require('jquery');</script>

现在您可以通过在您的 js 文件中使用它来使用您的 js 执行远程功能:

const {BrowserWindow} = require('electron').remote;
var theWindow = BrowserWindow.getFocusedWindow();

现在您可以使用以下命令设置、最大化、最小化和关闭应用程序:

theWindow.close();