简体   繁体   中英

C# How to turn off specific monitor?

I know how to turn on/off all monitors by using user32.dll.

SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) -1);
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM)  2);

But I want to turn on/off only single one.

@Dai is right. Use the Low-Level Monitor Configuration Functions can turn off a specified monitor.

The following is an example of selecting one monitor and turn off it, after 5 seconds turn it on.

#include <windows.h>
#include <vector>
#include <lowlevelmonitorconfigurationapi.h>

#pragma comment(lib, "Dxva2.lib")

const BYTE PowerMode = 0xD6;  // VCP Code defined in VESA Monitor Control Command Set (MCCS) standard
const DWORD PowerOn = 0x01;
const DWORD PowerOff = 0x04;

// Monitor description struct
struct MonitorDesc
{
    HANDLE hdl;
    DWORD power;
};

// Monitor enumeration callback
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
    std::vector<MonitorDesc>* pMonitors = reinterpret_cast<std::vector<MonitorDesc>*>(dwData);

    DWORD nMonitorCount;
    if (GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &nMonitorCount))
    {
        PHYSICAL_MONITOR* pMons = new PHYSICAL_MONITOR[nMonitorCount];

        if (GetPhysicalMonitorsFromHMONITOR(hMonitor, nMonitorCount, pMons))
        {
            for (DWORD i = 0; i < nMonitorCount; i++)
            {
                MonitorDesc desc;
                desc.hdl = pMons[i].hPhysicalMonitor;

                pMonitors->push_back(desc);
            }
        }
        delete[] pMons;
    }
    return TRUE;
}

// Switch monitor power
void MonitorSwitch(MonitorDesc& monitor, DWORD mode)
{
    if (monitor.power == mode)
        return;

    SetVCPFeature(monitor.hdl, PowerMode, mode);
    monitor.power = mode;
}

int main()
{
    std::vector<MonitorDesc> monitors;
    EnumDisplayMonitors(NULL, NULL, &MonitorEnumProc, reinterpret_cast<LPARAM>(&monitors));

    // Init
    for (auto& monitor : monitors)
    {
        monitor.power = PowerOn;
    }

    // Here select the first one monitor as example
    MonitorDesc targetMonitor = monitors[0];

    // turn off
    if (targetMonitor.power == PowerOn)
    {
        MonitorSwitch(targetMonitor, PowerOff);
    }

    Sleep(5000);

    // turn on
    if (targetMonitor.power == PowerOff)
    {
        MonitorSwitch(targetMonitor, PowerOn);
    }
}

You could always run ControlMyMonitor.exe from nirsoft.

As of version 1.20, you can turn monitors on and off using:

ControlMyMonitor.exe /SwitchValue "\\.\DISPLAY1\Monitor0" D6 1 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM