1. Creating and Initializing a BrowserWindow Instance
First, create an instance of BrowserWindow by passing an options object to its constructor to set the initial window size.
javascriptconst { app, BrowserWindow } = require('electron'); function createWindow() { let win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); win.loadURL('https://example.com'); } app.on('ready', createWindow);
In this example, the window is initialized to 800x600 pixels.
2. Dynamically Adjusting Window Size
To change the window size during application runtime, use the setSize method, which allows specifying new width and height values.
javascriptfunction resizeWindow() { let win = BrowserWindow.getFocusedWindow(); if (win) { win.setSize(1024, 768); } }
This function assumes the window has focus and adjusts its size to 1024x768 pixels.
3. Listening for Window Events
When you need to perform actions upon window size changes, listen for the resize event in Electron.
javascriptwin.on('resize', () => { const { width, height } = win.getBounds(); console.log(`Window size: ${width}x${height}`); });
This code logs the new size whenever the window size changes.
4. Using Maximize and Minimize Functions
The BrowserWindow class in Electron supports maximizing and minimizing windows:
javascriptfunction maximizeWindow() { let win = BrowserWindow.getFocusedWindow(); if (win) { win.maximize(); } } function minimizeWindow() { let win = BrowserWindow.getFocusedWindow(); if (win) { win.minimize(); } }
These methods control the window's state rather than directly setting its dimensions.
Conclusion
Using the BrowserWindow class in Electron, you can flexibly manage window size and state. Set the initial size when creating the window, dynamically adjust size during runtime based on application needs, or respond to size change events. These features make Electron highly powerful and adaptable for desktop application development.