If your Electron app remembers the last window position and restores it on launch, it may cause an issue for those who have a secondary screen.
Because secondary screens can be detached in a certain situation, the window can be outside of the screen when restoring the position but the screen was not connected.
To detect this, you can check if a given position is inside of any of the screens like so:
import { remote, ipcRenderer, BrowserWindow } from 'electron'
const { screen } = remote
function isWithinDisplayBounds(pos: { x: number, y: number }) {
const displays = screen.getAllDisplays()
return displays.reduce((result, display) => {
const area = display.workArea
return (
result ||
(pos.x >= area.x &&
pos.y >= area.y &&
pos.x < area.x + area.width &&
pos.y < area.y + area.height)
)
}, false)
}
Then, if it's out of bounds, it should be moved into the primary screen:
const isOnScreen = isWithinDisplayBounds({ x, y })
const primaryScreenBounds = screen.getPrimaryDisplay().bounds
if (!isOnScreen) {
x = (primaryScreenBounds.width - w) / 2
y = (primaryScreenBounds.height - h) / 2
}
- My app: Inkdrop - Markdown note-taking app
- Follow me on Twitter & Instagram
Top comments (0)