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

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


Try the following code

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

This will return true if Windows identifies a display device with index (AKA identity) 0 (this is what the display control panel uses internally). Otherwise, it will return false false. So by checking the first possible index (which I marked as the default argument), you can find out whether any display device is connected (or at least identified by Windows, which is essentially what you're looking for).


Seems that there is some kind of "default monitor" even if no real monitor is connected.The function below works for me (tested on a Intel NUC and a Surface 5 tablet).

The idea is to get the device id and check if it contains the string "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;}