[原创]C#省电绝招-程序控制显示器的关闭和恢复
原创文章,未赋予转载复制的权利。如需转载,请联系博主
通过C#控制显示器的关闭和恢复
本文讲述如何使用C#程序来控制显示器的打开与关闭
下面我们来做一个这样的关闭程序。查询msdn的api后发现,其实这个小功能实现起来非常简单,利用WM_SYSCOMMAND消息的SC_MONITORPOWER参数就可以控制显示器的状态。下面是完整的C#代码,实现过程中使用了.net interop来发送我们的控制消息。
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Runtime.InteropServices;
5 using System.Threading;
6
7 namespace ShutDownMonitor
8 {
9 class Program
10 {
11
12 static void Main(string[] args)
13 {
14 Console.WriteLine("Monitor is being shut off");
15 Thread.Sleep(1000);
16 Monitor.TurnOff();
17 Thread.Sleep(2000);
18 Monitor.TurnOn();
19 Console.WriteLine("Monitor is turned on");
20 }
21
22 }
23
24 class Monitor
25 {
26 [DllImport("user32.dll")]
27 public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
28 public static void TurnOn()
29 {
30 SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, -1);
31 }
32
33 public static void TurnOff()
34 {
35 SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
36 }
37
38 static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
39 const uint WM_SYSCOMMAND = 0x0112;
40 const int SC_MONITORPOWER = 0xf170;
41 }
42 }
43
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Runtime.InteropServices;
5 using System.Threading;
6
7 namespace ShutDownMonitor
8 {
9 class Program
10 {
11
12 static void Main(string[] args)
13 {
14 Console.WriteLine("Monitor is being shut off");
15 Thread.Sleep(1000);
16 Monitor.TurnOff();
17 Thread.Sleep(2000);
18 Monitor.TurnOn();
19 Console.WriteLine("Monitor is turned on");
20 }
21
22 }
23
24 class Monitor
25 {
26 [DllImport("user32.dll")]
27 public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
28 public static void TurnOn()
29 {
30 SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, -1);
31 }
32
33 public static void TurnOff()
34 {
35 SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
36 }
37
38 static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
39 const uint WM_SYSCOMMAND = 0x0112;
40 const int SC_MONITORPOWER = 0xf170;
41 }
42 }
43