Electron: How can I get Screen from BrowserWindow?
Asked Answered
O

4

6

I want to know where BrowserWindow located from two or more screens. I guess Electron API doesn't give a method. How can I do that? Is there any way or something??

Orly answered 11/8, 2017 at 11:43 Comment(1)
can you provide more info about what you want exactly ? thanks.Lorenalorene
B
7

There is no direct way to achieve this. But following can definitely serve your purpose.

const {BrowserWindow, screen} = require('electron');

let window = new BrowserWindow();

// Load a URL and show the window first

const winBounds = window.getBounds();
const whichScreen = screen.getDisplayNearestPoint({x: winBounds.x, y: winBounds.y});
// Returns the screen where your window is located

This is tested to be working.

Babel answered 30/5, 2018 at 2:10 Comment(1)
Tested locally, and only almost works. Problem (on mac) is that your window may only show on one screen, but it's origin may be moved off the screen it's showing on. I can reproduce my moving the screen until the left hand side is off the monitor, if only by a few points.Triglyph
M
1

For detecting which screen has your window inside, after you created your window:

const win = new BrowserWindow({...});

Using Screen API and getDisplayNearestPoint() method, you can get the screen coordinates:

const winBounds = win.getBounds();
const distScreen = screen.getDisplayNearestPoint({x: winBounds.x, y: winBounds.y})

And also, for if you want to get which screen has the mouse cursor inside, use:

let cursor = screen.getCursorScreenPoint();
let distScreen = screen.getDisplayNearestPoint({x: cursor.x, y: cursor.y});
Mousetail answered 9/4, 2020 at 16:11 Comment(0)
S
0

Electron defines a screen API which contains the screen.getAllDisplays() method returning an array of Display objects that are currently available.

I guess you would have to loop over the list of displays, get their bounds and check if they intersect with your window's own bounds. Or maybe use the workArea property? Unfortunately, I have only one display so I can't check how it would work...

Selfknowledge answered 11/8, 2017 at 12:54 Comment(0)
V
0

screen.getDisplayMatching should be a better solution, like below:

mainWindow.on("move", () => {
const windowBounds = window.getBounds();
const currentDisplay = screen.getDisplayMatching(windowBounds);

// Perform your actions here..
console.log(currentDisplay);
});

Hope it help you.

Verrucose answered 3/6 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.