Thursday, March 14, 2019

Turn off monitor - C++

monitor_off.png

My brother asked me how can he turn off the monitor. He showed me a PowerShell script

start powershell (Add-Type '[DllImport(\"user32.dll\")]^public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2); exit

My reaction was “what the heck, seriously you can do that with PowerShel, like, invoke a function in a DLL file just like that?!”.

I asked him, why he wants to turn off the monitor. He said sometime he uses his laptop just to play music. I get that, he’d like to enjoy music using portable DAC at Uni sometime, monitor off to save battery. And he complained that script leaves a console window open even after monitor wakes up. I suggested him to build a win32 app just for that.

A simple console application would replace the PowerShell script, which just do the same but in better way.

Start a new empty c++ project using Visual Studio and then add a new source file

#include <windows.h>

int main(int argc, CHAR* argv[])
{
	SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
	return 0;
}

This one basically does the same thing but much faster when it is native win32. But it shows the same console window. Alright, change SendMessage to PostMessage make the console window goes away as soon as monitor turns off. Not perfect, but yeah, it’s certainly better.

Why wouldn’t I make it as a win32 app? Virtually the same, start with empty project, then add a cpp file and compile.

#include <windows.h>

int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
	//Sleep(1000); // test if it still shows a console window
	PostMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
	return 0;
}

Next step is to add an icon resource and done.
It was easy! But if you are lazy here is the binary
[attach=downloads/monitor_off/MonitorOff_1s.rar]MonitorOff_1s.rar[/attach]