动态调整电子app窗口的大小

时间:2017-10-04 12:00:01

标签: javascript electron atom-editor

Main.js

const {app, BrowserWindow} = require('electron');
const path = require('path');
const url = require('url');

let win;  
app.on('ready', createWindow);
function createWindow () {
    // Create the browser window.
    win = new BrowserWindow();
    // and load the index.html of the app.
    win.loadURL(url.format({
        pathname: path.join(__dirname, 'main.html'),
        protocol: 'file:',
        slashes: true
    }));
    // Open the DevTools.
    win.webContents.openDevTools();
    // Emitted when the window is closed.
    win.on('closed', () => {
        win = null;
    });
}
// 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 (win === null) {
        createWindow();
    }
});

main.html中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MyApp</title>
</head>
<body>

<h1>Hello !</h1>
<button id="resizeBtn">Resize</button>
</body>
</html>

我希望如果用户点击按钮,那么一个函数应该触发并改变已经打开的主窗口的大小。我知道win.setSize(width,height)可以做到这一点,但我不知道如何把这个在一个函数中。我不知道如何在main.js中获取Button的引用来添加一个事件监听器或如何获取当前窗口并应用一些操作。我是电子新手! 感谢

3 个答案:

答案 0 :(得分:1)

简短回答(来自手机):使用ipcRender模块向main发送事件并调用resize方法。

答案很长: 我找不到电子游乐场了!

// In renderer process (web page).
const {ipcRenderer} = require('electron')
const myResizeBtn = document.getElementById('resizeBtn')
myResizeBtn.addEventListener('click', function () {
  ipcRenderer.send('resize-me-please')
})

// in main.js

const {ipcMain} = require('electron')
ipcMain.on('resize-me-please', (event, arg) => {
  win.setSize(width,height)
})

答案 1 :(得分:0)

如今,您可以使用代码获取当前的BrowserWindow,并按如下所示调整其大小:

const {remote} = require('electron');

const win = remote.getCurrentWindow();

let height = 400;
let width = 200; 
let animate = false;

win.setSize(width, height, animate);

关于BrowserWindow.setSize(),它具有三个参数。

  1. 宽度整数
  2. 高度整数
  3. 动画布尔值(可选)macOS

您可以在官方文档https://www.electronjs.org/docs/api/browser-window中找到有关BrowserWindow setSize方法的更多信息。

答案 2 :(得分:0)

使用这个, 这有效


    function createWindow() {
      // Create the browser window.
      const mainWindow = new BrowserWindow({ useContentSize: true });
      const view = new BrowserView();
      mainWindow.setBrowserView(view);
      view.setBounds({ x: 0, y: 0, width: 800, height: 600 });
      view.setAutoResize({ width: true, height: true });
      view.webContents.loadURL("https://youtube.com");
    }