Search code examples
electron

Detect when Electron app is moved to different monitor/display


I'm building an Electron app, and the way I have the window sizes configured is to base itself on % of the monitor/display dimension.

However I quickly noticed an issue when the user has more than one monitor. The initial window dimensions are calculated and never re-calculated for when the user changes to the second monitor, and due to this in the case that the monitors aren't the same dimension, the window has the wrong size on the other monitor.

Essentially what I'm looking for here is any sort of event which will detect when the user changes the monitor he/she is using the app on, and in this way I will be able to re-calculate the window size based on the new monitor dimension.


Solution

  • You can use the move event of the BrowserWindow in combination with the screen API like such:

    const {app, BrowserWindow} = require("electron");
    
    let mainWindow;
    
    app.on("ready", function() {
        mainWindow = new BrowserWindow();
    
        // Screen module must be imported after app is ready (as per docs)
        const {screen} = require("electron");
    
        mainWindow.on("move", () => {
            const bounds = mainWindow.getBounds();
            const currentDisplay = screen.getDisplayNearestPoint({x: bounds.x, y: bounds.y});
    
            // Perform your actions here..
            console.log(currentDisplay);
        });
    });
    

    In the event handler, you can then obtain the display metrics and perform any actions you need based on that.

    Note that the move event fires very frequently. You may check out the moved event or implement some form of debouncing yourself if needed.