Electron: How can I get Screen from BrowserWindow?

Viewed 3871

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

3 Answers

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.

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