C# - 控制螢幕 Monitor Control

C# - 控制螢幕 Monitor Control

參考:Complete guide on How to turn a monitor on/off/standby

以下程式碼,透過 button1 控制項 Click 事件執行 SendMessage() 方法,通知 Monitor 操作【ON】、【OFF】、【StandBy】等動作。

要是在有多螢幕的情形,應該是通通關閉吧?我沒有多各螢幕可以測試,所以不能夠確定。

程式碼:

  1. using System;
  2. using System.Runtime.InteropServices; // to import Dll
  3. using System.Windows.Forms;
  4. namespace MonitorControl
  5. {
  6. public partial class Form1 : Form
  7. {
  8. public enum MonitorState : int
  9. {
  10. MONITOR_ON = -1,
  11. MONITOR_OFF = 2,
  12. MONITOR_STANBY = 1
  13. } ;
  14. public Form1( )
  15. {
  16. InitializeComponent( );
  17. }
  18. public int WM_SYSCOMMAND = 0x0112;
  19. public int SC_MONITORPOWER = 0xF170;
  20. [DllImport( "user32.dll" ) ]
  21. private static extern int SendMessage( int hWnd, int hMsg, int wParam, int lParam);
  22. private void button1_Click( object sender, EventArgs e)
  23. {
  24. SendMessage( this.Handle.ToInt32 ( ), WM_SYSCOMMAND, SC_MONITORPOWER, ( int ) MonitorState.MONITOR_OFF );
  25. }
  26. }
  27. }