有没有办法检测显示器是否插了电?

Is there a way to detect if a monitor is plugged in?

本文关键字:是否 显示器 检测 有没有      更新时间:2023-10-16

我有一个用c++编写的自定义应用程序,它控制连接到嵌入式系统的监视器的分辨率和其他设置。有时系统是无头引导并通过VNC运行的,但可以稍后(引导后)插入监视器。如果发生这种情况,监视器将不提供视频,直到监视器启用。我发现调用"displayswitch/clone"会使显示器上升,但我需要知道何时连接显示器。我有一个计时器,每5秒运行一次,寻找监视器,但我需要一些API调用,可以告诉我监视器是否连接。

这里有一些伪代码来描述我所追求的(当计时器每5秒过期时执行的内容)。

if(If monitor connected) 
{
   ShellExecute("displayswitch.exe /clone);
}else
{
   //Do Nothing
}

我已经尝试GetSystemMetrics(SM_CMONITORS)返回监视器的数量,但如果监视器连接与否,它返回1。还有其他想法吗?

谢谢!

试试下面的代码

BOOL IsDisplayConnected(int displayIndex = 0)
{
    DISPLAY_DEVICE device;
    device.cb = sizeof(DISPLAY_DEVICE);
    return EnumDisplayDevices(NULL, displayIndex, &device, 0);
}

这将返回true如果Windows识别一个显示设备索引(AKA标识)0(这是显示控制面板内部使用)。否则,将返回false false。因此,通过检查第一个可能的索引(我将其标记为默认参数),您可以找出是否连接了任何显示设备(或至少由Windows识别,这实际上是您正在寻找的)。

似乎有某种"默认监视器";即使没有连接真正的监视器。下面的功能对我来说是有效的(在英特尔NUC和Surface 5平板电脑上测试)。

这个想法是获取设备id并检查它是否包含字符串"default_monitor"

bool hasMonitor()
{
    // Check if we have a monitor
    bool has = false;
    // Iterate over all displays and check if we have a valid one.
    //  If the device ID contains the string default_monitor no monitor is attached.
    DISPLAY_DEVICE dd;
    dd.cb = sizeof(dd);
    int deviceIndex = 0;
    while (EnumDisplayDevices(0, deviceIndex, &dd, 0))
    {
        std::wstring deviceName = dd.DeviceName;
        int monitorIndex = 0;
        while (EnumDisplayDevices(deviceName.c_str(), monitorIndex, &dd, 0))
        {   
            size_t len = _tcslen(dd.DeviceID);
            for (size_t i = 0; i < len; ++i)
                dd.DeviceID[i] = _totlower(dd.DeviceID[i]);
            has = has || (len > 10 && _tcsstr(dd.DeviceID, L"default_monitor") == nullptr);
            ++monitorIndex;
        }
        ++deviceIndex;
    }
    return has;
}