如何检测显示器是否关闭/打开?

时间:2015-11-13 12:48:40

标签: c# .net winforms

问题是,在文本文件中,我看到了所有结果 - TrueNot。 即使我关闭显示器5-10秒并打开它,文本文件也会显示True

不确定为什么它没有检测到它。

我试过了:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Management;

namespace Detect_Monitor_Settings
{
    public partial class Form1 : Form
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);

        [FlagsAttribute]
        public enum EXECUTION_STATE : uint
        {
            ES_AWAYMODE_REQUIRED = 0x00000040,
            ES_CONTINUOUS = 0x80000000,
            ES_DISPLAY_REQUIRED = 0x00000002,
            ES_SYSTEM_REQUIRED = 0x00000001
            // Legacy flag, should not be used.
            // ES_USER_PRESENT = 0x00000004
        }

        StreamWriter w = new StreamWriter(@"e:\monitordetector.txt");

        public Form1()
        {
            InitializeComponent();
        }

        private void DetectScreenName()
        {
           if (stopdetecting == false)
            {
                var query = "select * from WmiMonitorBasicDisplayParams";
                using (var wmiSearcher = new ManagementObjectSearcher("\\root\\wmi", query))
                {
                    var results = wmiSearcher.Get();
                    foreach (ManagementObject wmiObj in results)
                    {
                        // get the "Active" property and cast to a boolean, which should 
                        // tell us if the display is active. I've interpreted this to mean "on"
                        var active = (Boolean)wmiObj["Active"];
                        w.WriteLine(active.ToString());
                    }
                }
            }
        }



        private void Form1_Load(object sender, EventArgs e)
        {

        }

        bool stopdetecting = false;
        int counttimer1 = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            DetectScreenName();
            counttimer1 += 1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            w.Close();
            stopdetecting = true;
            timer1.Stop();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

根据文档Active

  

表示活动监视器。

这并不意味着显示器未处于省电模式。它只是告诉你它是否被禁用 - 通常,它用于检测你是否有多个监视器(例如“是活动监视器的数量是否大于1?”)。