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

Electron如何检测显示器拔出及当前活跃显示器的插拔事件

检测当前活跃显示器拔出事件的实现方案

首先,你需要监听屏幕设备的移除事件,同时结合当前应用窗口所在的显示器信息来判断是否是活跃显示器被拔出。以下分不同环境给出具体实现:

桌面应用环境(以Electron为例)

Electron的screen模块提供了直接的显示器事件监听能力,搭配窗口边界匹配可以精准判断活跃显示器状态:

  • 监听display-removed事件:该事件会在任意显示器被移除时触发,回调参数包含被移除的显示器对象
  • 对比被移除显示器ID与当前应用窗口所在显示器ID,确认是否为活跃显示器

示例代码:

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

// 获取当前聚焦窗口所在的显示器
function getActiveDisplay() {
  const focusedWindow = BrowserWindow.getFocusedWindow();
  if (!focusedWindow) return null;
  return screen.getDisplayMatching(focusedWindow.getBounds());
}

// 绑定显示器移除事件监听
screen.on('display-removed', (event, removedDisplay) => {
  const currentActiveDisplay = getActiveDisplay();
  if (currentActiveDisplay && removedDisplay.id === currentActiveDisplay.id) {
    console.log('当前活跃显示器已被拔出');
    // 在此添加业务逻辑:比如自动切换窗口到其他显示器、弹出提示等
  }
});

额外提示:

  • 若应用有多窗口,可根据需求调整getActiveDisplay逻辑,比如固定监听主窗口而非聚焦窗口
  • screen.getDisplayMatching()比getPrimaryDisplay()更准确,因为主显示器不一定是当前应用所在的显示器

浏览器环境

浏览器原生window.screen没有直接的显示器移除事件,可通过监听窗口resize事件结合屏幕信息变化间接判断:

let prevDisplayCount = window.screen.length; // 仅部分浏览器支持多显示器数量获取

window.addEventListener('resize', () => {
  const currentDisplayCount = window.screen.length;
  if (currentDisplayCount < prevDisplayCount) {
    console.log('检测到显示器数量减少,可能有显示器被拔出');
    // 浏览器环境下多显示器检测兼容性较差,仅作参考
    prevDisplayCount = currentDisplayCount;
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:27:21