Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a custom application written in C++ that controls the resolution and other settings on a monitor connected to an embedded system. Sometimes the system is booted headless and run via VNC, but can have a monitor plugged in later (post boot). If that happens he monitor is fed no video until the monitor is enabled. I have found calling "displayswitch /clone" brings the monitor up, but I need to know when the monitor is connected. I have a timer that runs every 5 seconds and looks for the monitor, but I need some API call that can tell me if the monitor is connected.

Here is a bit of psudocode to describe what I'm after (what is executed when the timer expires every 5 seconds).

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

I have tried GetSystemMetrics(SM_CMONITORS) to return the number of monitors, but it returns 1 if the monitor is connected or not. Any other ideas?

Thanks!

like image 789
martinarcher Avatar asked Jan 11 '13 21:01

martinarcher


1 Answers

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).

like image 81
Yam Marcovic Avatar answered Oct 13 '22 07:10

Yam Marcovic