要打开/关闭,您可以使用以下类:
public static class MonitorHelper
{
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);
public static void TurnOn()
{
SendMessage(-1, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_ON);
}
public static void TurnOff()
{
SendMessage(-1, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);
}
const int SC_MONITORPOWER = 0xF170;
const int WM_SYSCOMMAND = 0x0112;
const int MONITOR_ON = -1;
const int MONITOR_OFF = 2;
}
类的用法MonitorHelper
:
class Program
{
static void Main(string[] args)
{
MonitorHelper.TurnOff();
Thread.Sleep(TimeSpan.FromSeconds(2));
MonitorHelper.TurnOn();
}
}
如果你想通过打开/关闭监视器来安排你的任务,你可以使用Quartz.NET。
Quartz.NET 示例:
职位类别:
class MonitorJob : IJob
{
public void Execute(IJobExecutionContext context)
{
MonitorHelper.TurnOff();
Thread.Sleep(TimeSpan.FromSeconds(2));
MonitorHelper.TurnOn();
}
}
配置代码:
ISchedulerFactory schedFact = new StdSchedulerFactory();
IScheduler sched = schedFact.GetScheduler();
IJobDetail job = JobBuilder.Create<MonitorJob>()
.WithIdentity("monitorJob", "group")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("monitorTrigger", "group")
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInMinutes(1).RepeatForever())
.Build();
sched.ScheduleJob(job, trigger);
sched.Start();
带有 PostMessage 的 MonitorHelper 类:
class MonitorHelperEx
{
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
public static void TurnOn()
{
PostMessageSafe(new IntPtr(-1), WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_ON);
}
public static void TurnOff()
{
PostMessageSafe(new IntPtr(-1), WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);
}
static void PostMessageSafe(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
bool returnValue = PostMessage(hWnd, msg, wParam, lParam);
if (!returnValue)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
static readonly IntPtr SC_MONITORPOWER = new IntPtr(0xF170);
static readonly uint WM_SYSCOMMAND = 0x0112;
static readonly IntPtr MONITOR_ON = new IntPtr(-1);
static readonly IntPtr MONITOR_OFF = new IntPtr(2);
}