There was a time when Windows automatically changed brightness depending on power status. For example, when my laptop is plugged in the brightness is 100%, and when it's on battery the brightness is 70%.
It worked well till Windows 10 1903 update. After that, the brightness remained the same after unplugging the cable. The question was asked on Microsoft website (Link), but it is still open.
Let's now fix it using the latest .NET!
First of all, create a WorkerService.
Now we need to convert it to WindowsService.
First add NuGet package
Microsoft.Extensions.Hosting.WindowsServices
Then in
Program.cs
callUseWindowsService()
inCreateHostBuilder
:
Our base Windows Service is ready.
Now let's back to our main issue.
This utility is split into 2 parts: the first checks the power status, and the second sets the brightness.
Part 1. Check the Power status
Let's now see what is here.
BatteryFlag
describes the current battery status. It has the valueNoSystemBattery
which we use to know if the device is a desktop or a laptop.AcLineStatus
describes if a device is charging (Online
) or not (Offline
).GetPowerState
method calls the WinApi method to get the current power state.
Part 2. Creating the Brightness Service
Using WMI we get and set the brightness.
The last part is left. We need to call our services. Open Worker.cs
and replace ExecuteAsync
method content with:
So we check for the power state. If our device is a desktop (NoSystemBattery
) just stop the service. Else get the current brightness and compare it to the desired. If they are different we call the BrightnessService
. To monitor the status and react to the power state changes we wait for 1 second and then try to set the brightness again.
Bonus
Create install/uninstall scripts.
Install script
Save and copy the bat file to the output directory and run as administrator. The WindowsService should appear in the list of services
Uninstall script
Save and copy the bat file to the output directory and run as administrator. The WindowsService should disappear from the list of services
P.S.
After some days of usage, I found the flickering of the screen. It happens because Windows has another place where it stores the current brightness settings. Let's now fix the issue.
Add new method to the BrightnessService
:
Now call this method in SetBrigthness
.
That's it.
You can download the solution on my GitHub: WindowsService