Search code examples
javaswingmonitor

How do you turn on and off a monitor from within a Java application?


How do you turn on and off a monitor from within a Java application?

In case you're wondering why, this is a kiosk style application where it would be great to turn off the monitors at night. Yes you can do it within the screensaver settings of the machine, but it would be great to do it programatically and avoid having to configure it on each machine.


Solution

  • Assuming you deploy your Java Applications on Windows, you can use this WIN32API functions:

    // turn off monitor
    SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) 2); 
    
    // turn on monitor
    SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (LPARAM) -1);    
    

    Then you write a little C-JNI wrapper to functions that call the mentioned SendMessage and use the little wrapper to turn off the monitor from Java.