Control Monitor Power Using C#

Introduction

The Monitor power is handled by sending the right message to the Operating System. The code may change depending on the Operating System. This code only works with the Windows Operating System.

Interpo Service

  1. using System.Runtime.InteropServices   
The System.Runtime.InteropServices namespace provides a variety of members that support COM interop. The most important attributes are DllImportAttribute that can be used to define platform invoke methods for accessing unmanaged APIs and MarshalAsAttribute that is used to specify how data can marshalled between managed and unmanaged memory.
  1. private const int HWND_BROADCAST = 0xFFFF;//the message is sent to all    
  2.     
  3. //top-level windows in the system    
  4.     
  5. private const int SC_MONITORPOWER = 0xF170;    
  6.     
  7. private const int WM_SYSCOMMAND = 0x112;  
The WM_SYSCOMMAND message is sent to a window when the user chooses a command from the window menu.

SC_MONITORPOWER is a command sent using the WM_SYSCOMMAND message to control the monitor's power.

Monitor State
  1. private const int MONITOR_ON = -1;    
  2.     
  3. private const int MONITOR_OFF = 2;    
  4.     
  5. private const int MONITOR_STANBY = 1;    

    -1 (the display is power ng on)
    1 (the display is going to low power)
    2 (the display is being shut off)

The preceding code sets the state of the monitor.

Using the DllImport Attribute

Now use the DllImport Attribute like the following:

  1. [DllImport("user32.dll")]   
The DllImport attribute is very useful when reusing existing unmanaged code in a managed application.

SendMessage function
  1. private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);   
Declare the SendMessage function that calls the window procedure for the specified window.

Now call the SendMessage function in the Main class.
  1. SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);  
Conclusion

Various types of SendMessage functions exist, so use all the functions and have fun.

Reference 

Up Next
    Ebook Download
    View all
    Learn
    View all