How to find if electron app is in foreground?

﹥>﹥吖頭↗ 提交于 2020-08-19 17:05:54

问题


I have a requirement where I want to perform an action inside the electron app only when it is in foreground.

It is an electron-react application. On mounting of a component, I want to schedule a periodic task which only runs when the app is in focus or is being used by the user. And pause the task when the app goes in background.

How can we detect the Electron app being in foreground?


回答1:


You can use the isFocused method from BrowserWindow. To get your own BrowserWindow, you can do this :

remote.BrowserWindow.getAllWindows();

This will return all your app's windows. So to get the first / primary window, you could deconstruct the array like this :

const [yourBrowserWindow] = remote.BrowserWindow.getAllWindows();
console.log(yourBrowserWindow.isFocused());



回答2:


You can use the focus / blur events on your BrowserWindow to be notified when the app is focused / unfocused.

mainWindow = new BrowserWindow({})

mainWindow.on('focus', () => {
    console.log('window got focus')
})

mainWindow.on('blur', () => {
    console.log('window blur')
})

You may want to update the component's state within these event handlers or use any other method to keep track of the current focus status.

This assumes that you have a single application window. If you have multiple, you'll need to extend the check to cover all of your windows.



来源:https://stackoverflow.com/questions/55474279/how-to-find-if-electron-app-is-in-foreground

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!