Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change laptop screen brightness from a java application?

I want to create a java application to change the laptop screen brightness on windows xp/7. Please help

like image 613
Sujal Patel Avatar asked Apr 08 '13 13:04

Sujal Patel


1 Answers

As others have stated, there isn't any official API to use. However, using Windows Powershell (which comes with windows I believe, so no need to download anything) and WmiSetBrightness, one can create a simple workaround that should work on all windows PCs with visa or later installed.

All you need to do is copy this class into your workspace:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class BrightnessManager {
    public static void setBrightness(int brightness)
            throws IOException {
        //Creates a powerShell command that will set the brightness to the requested value (0-100), after the requested delay (in milliseconds) has passed. 
        String s = String.format("$brightness = %d;", brightness)
                + "$delay = 0;"
                + "$myMonitor = Get-WmiObject -Namespace root\\wmi -Class WmiMonitorBrightnessMethods;"
                + "$myMonitor.wmisetbrightness($delay, $brightness)";
        String command = "powershell.exe  " + s;
        // Executing the command
        Process powerShellProcess = Runtime.getRuntime().exec(command);

        powerShellProcess.getOutputStream().close();

        //Report any error messages
        String line;

        BufferedReader stderr = new BufferedReader(new InputStreamReader(
                powerShellProcess.getErrorStream()));
        line = stderr.readLine();
        if (line != null)
        {
            System.err.println("Standard Error:");
            do
            {
                System.err.println(line);
            } while ((line = stderr.readLine()) != null);

        }
        stderr.close();

    }
}

And then call

BrightnessManager.setBrightness({brightness});

Where {brightness} is the brightness you want to set the screen display at with 0 being the dimmest supported brightness and 100 being the brightest.

Big thanks to anquegi for the powershell code found here that I adapted to run this command.

like image 115
Darty11 Avatar answered Oct 06 '22 00:10

Darty11