Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach disabled display device with WinAPI

Tags:

c++

winapi

My problem is enabling a disabled monitor with ChangeDisplaySettingsEx. I guess it is not rocket science but after some digging it still looks impossible. I found a way to disable all secondary displays basing on Microsoft code sample found here. While it needed only basic tweaking to work, re-attaching never worked. What I was trying to do was:

1. Initialize DisplayDevice

BOOL            FoundSecondaryDisp = FALSE;
DWORD           DispNum = 0;
DISPLAY_DEVICE  DisplayDevice;
LONG            Result;
TCHAR           szTemp[200];
int             i = 0;
DEVMODE   defaultMode;
ZeroMemory(&DisplayDevice, sizeof(DisplayDevice));
DisplayDevice.cb = sizeof(DisplayDevice);

2. Find all devices

while (EnumDisplayDevices(NULL, DispNum, &DisplayDevice, 0))
{
    ZeroMemory(&defaultMode, sizeof(DEVMODE));
    defaultMode.dmSize = sizeof(DEVMODE);
    //point 3 goes here
}

3. Detect detached device

if (!(DisplayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP))

4. Enable device

DEVMODE    DevMode;
ZeroMemory(&DevMode, sizeof(DevMode));
DevMode.dmSize = sizeof(DevMode);
DevMode.dmFields = DM_POSITION | DM_PELSWIDTH | DM_PELSHEIGHT;
DevMode.dmPelsWidth = 1920;
DevMode.dmPelsHeight = 1080;
Result = ChangeDisplaySettingsEx(DisplayDevice.DeviceName, &DevMode, NULL, CDS_UPDATEREGISTRY, NULL);
ChangeDisplaySettingsEx(NULL, NULL, NULL, NULL, NULL);

Last point returns DISP_CHANGE_FAILED code and it does not enable any display. Did anyone have some similar experience?

like image 207
Artur Avatar asked Oct 31 '22 10:10

Artur


1 Answers

Try adding CDS_NORESET to your first call to ChangeDisplaySettingsEx.

This one works:

ChangeDisplaySettingsEx((LPCWSTR)DisplayDevice.DeviceName, &DevMode, NULL, CDS_UPDATEREGISTRY | CDS_NORESET, NULL);
ChangeDisplaySettingsEx(NULL, NULL, NULL, 0, NULL);

This one does NOT work:

ChangeDisplaySettingsEx((LPCWSTR)DisplayDevice.DeviceName, &DevMode, NULL, CDS_UPDATEREGISTRY | CDS_RESET, NULL);
ChangeDisplaySettingsEx(NULL, NULL, NULL, 0, NULL);

This one also does NOT work:

ChangeDisplaySettingsEx((LPCWSTR)DisplayDevice.DeviceName, &DevMode, NULL, CDS_UPDATEREGISTRY, NULL);
ChangeDisplaySettingsEx(NULL, NULL, NULL, 0, NULL); 
like image 155
digitalsteez Avatar answered Nov 08 '22 05:11

digitalsteez