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
- 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.
- private const int HWND_BROADCAST = 0xFFFF;
-
-
-
- private const int SC_MONITORPOWER = 0xF170;
-
- 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
- private const int MONITOR_ON = -1;
-
- private const int MONITOR_OFF = 2;
-
- 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:
- [DllImport("user32.dll")]
The
DllImport attribute is very useful when reusing existing unmanaged code in a managed application.
SendMessage function
- 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.
- 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