Electron:使浏览器 window 卡在屏幕的一侧

Electron: Make the browser window stuck to the side of screen

我正在尝试制作一个固定在屏幕一侧的浏览器 window,我确实做到了,但是,当我将显示设置更改为较小的纵横比并将其调回时(我的测试方式)window 停留在它移动过的地方,而不是回到我屏幕的一侧。

这是我当前的浏览器代码window:

function createWindow() {
  const {width,height} = screen.getPrimaryDisplay().workAreaSize;
  const mainWindow = new BrowserWindow({
    frame: false,
    width: 500,
    height: 500,
    useContentSize: true,
    backgroundColor: '#000000',
    transparent: true,
     resizable: true,
    x: width - 500,
    y: height - 450,
    visibleOnAllWorkspaces: true,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true
    }
   
  });

我想知道 window 位置是否只得到 运行 一次然后 x 和 y 位置不会再次检查?

PS:我是 Electron 的新手,如果有任何提示,我们将不胜感激

您需要在每次显示设置更改时动态调整主要 window 的边界(可能是 macOS Dock 变得可见或隐藏,或者屏幕分辨率被设置为不同的宽高比,等等) .).

screen API 定义了应用可以监听的几个事件,包括 'display-metrics-changed':

Event: 'display-metrics-changed'

Returns:

  • event Event
  • display Display
  • changedMetrics String[]

Emitted when one or more metrics change in a display. The changedMetrics is an array of strings that describe the changes. Possible changes are bounds, workArea, scaleFactor and rotation.

您的 createWindow 函数可以这样更新(在 Electron Fiddle 中快速测试,可能需要更多调整):

function createWindow() {
  const {width,height} = screen.getPrimaryDisplay().workAreaSize;
  const mainWindow = new BrowserWindow({
    frame: false,
    width: 500,
    height: 500,
    useContentSize: true,
    backgroundColor: '#000000',
    transparent: true,
     resizable: true,
    x: width - 500,
    y: height - 450,
    visibleOnAllWorkspaces: true,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true
    }

  });

  screen.on('display-metrics-changed', (event, display, changedMetrics) =>
  {
    // console.log(display, changedMetrics);
    const {x, y, width, height} = display.workArea;
    // console.log(x, y, width, height);
    mainWindow.setBounds({x: width - 500, y: height - 450, width: 500, height: 500})
  });

}