I needed to be able to turn the monitors on and off at will, based on a set time. I could have written a bunch of code that allowed me to set the schedule etc., but instead, I wrote this console app. The app runs on the command line, and accepts a couple of arguments so that its then a simple case of setting a schedule via the Windows scheduler. If you put the EXE in the Windows system32 folder, you can call it directly, so to turn the monitors off at night, you'd just call [monitors off], and to turn on in the morning, you'd call [monitors on]. Obviously, a test is helpful, since by definition you cannot see what is happening! [Monitors test].
To do this, you will need to call on the Windows API, and a function called
SendMessage supports all sorts of weird and wonderful things, so we need to import this function call. The
SendMessage function takes arguments that are simple constants, which can be found if you're lucky on the MSDN website.
Using the Code
Const HWND_BROADCAST As Integer = &HFFFF
Const SC_MONITORPOWER As Integer = &HF170
Const WM_SYSCOMMAND As Short = &H112S
Dim instr As String = Command()
MsgBox("Usage, [on]/[off]/[test] ", _
"Need Command Switch")
_ Private Function SendMessage( ByVal Handle As Int32, _
ByVal wMsg As Int32, ByVal wParam As Int32, _
ByVal lParam As Int32) As Int32
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 1)
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2)
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, -1)
Points of Interest
This code works with dual monitors, and you can use it via VNC - which is handy if you are running a kiosk or information display. This code works fine, but you might want to look at Raymond Chen's code (one of the Windows developers). He says that it's wrong to broadcast the monitor power messages. Instead, you should create your own window, post the message to it (only), then run a message pump, and finally exit. I would argue that they should write the documentation of these mystical functions a little better, but you might like to look here for more information: http://blogs.msdn.com/oldnewthing/archive/2006/06/13/629451.aspx. As far as I can gather, it's safe to use this broadcast for this message, but if you delve into the
SendMessage() function, you need to be careful, as all top level windows will process the message which could lead to some interesting issues.
- V1.00: Works fine, I cobbled it together from some code written in C, and I adapted it for .NET; presumably, you can import into C# easily.