Hyunseob Lee
Hyunseob Lee

Reputation: 61

Electron: How can I get Screen from BrowserWindow?

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??

Upvotes: 6

Views: 6246

Answers (4)

Blake.Xie
Blake.Xie

Reputation: 11

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.

Upvotes: 1

m4heshd
m4heshd

Reputation: 970

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.

Upvotes: 7

Saji
Saji

Reputation: 2826

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});

Upvotes: 1

user8022331
user8022331

Reputation:

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...

Upvotes: 0

Related Questions