You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Dock的位置与方向?Electron屏幕API使用求助

区分任务栏/Dock的左右方向(Electron)

你可以通过对比workArea和bounds的X轴坐标差值来区分左右侧边的任务栏/Dock,结合你已有的宽高差判断逻辑,完整判断逻辑如下:

核心判断逻辑

  • 先通过宽高差值判断任务栏是在垂直方向(左右)还是水平方向(上下)
  • 垂直方向时,通过workArea.x与primaryBounds.x的关系区分左右:
    • 若workArea.x > primaryBounds.x → 任务栏在左侧(占用了屏幕左侧区域,工作区向右偏移)
    • 若workArea.x === primaryBounds.x且工作区宽度小于屏幕总宽度 → 任务栏在右侧(占用屏幕右侧区域)

完整代码示例

const { screen } = require('electron');

const getDockPosition = () => {
  const primaryDisplay = screen.getPrimaryDisplay();
  const { workArea, bounds: primaryBounds } = primaryDisplay;
  
  const screenWidth = primaryBounds.width;
  const screenHeight = primaryBounds.height;
  const workWidth = workArea.width;
  const workHeight = workArea.height;
  const workX = workArea.x;

  const widthDiff = screenWidth - workWidth;
  const heightDiff = screenHeight - workHeight;

  // 判断垂直方向(左右)
  if (widthDiff > heightDiff && widthDiff > 0) {
    return workX > primaryBounds.x ? 'left' : 'right';
  } 
  // 判断水平方向(上下)
  else if (heightDiff > widthDiff && heightDiff > 0) {
    return workArea.y > primaryBounds.y ? 'top' : 'bottom';
  }
  // 无任务栏或自动隐藏状态
  else {
    return 'none';
  }
};

// 使用示例
const dockPosition = getDockPosition();
console.log('Dock/任务栏位置:', dockPosition);

补充说明

  • 该逻辑兼容Windows、macOS系统的任务栏/Dock位置判断
  • 若任务栏设置为自动隐藏,workArea会和bounds完全重合,此时返回none,可根据需求单独处理这种场景

内容的提问来源于stack exchange,提问作者guanyu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:41:03