オン/オフにするには、次のクラスを使用できます。
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);
}