Skip to content

Instantly share code, notes, and snippets.

@WingTillDie
Last active July 28, 2023 11:08
Show Gist options
  • Save WingTillDie/14b694ee2760ddd5499086f4953488ac to your computer and use it in GitHub Desktop.
Save WingTillDie/14b694ee2760ddd5499086f4953488ac to your computer and use it in GitHub Desktop.
Toggle Screen Brightness via resuming an app
# Example applications:
# * Improves privacy by dimming screen to lowest brightness immediately
# * Extend battery life by toggling screen brightness (as a faster alternative to sleep/wake that doesn't locks the computer)
# ** Reduces carbon footprint
# Written in Powershell Core
# Load necessary .NET assembly
Add-Type -AssemblyName System.Windows.Forms
# Define the functions for Get-Brightness, Set-Brightness, and Toggle-Brightness
function Get-Brightness {
# Create CIM Session
$namespaceName = "root/wmi"
# Get the CIM instance
$instance = Get-CimInstance -Namespace $namespaceName -ClassName WmiMonitorBrightness
# Print current brightness
$currentBrightness = $instance.CurrentBrightness
Write-Output "$currentBrightness"
}
function Set-Brightness ($brightness) {
$namespaceName = "root/WMI"
$className = "WmiMonitorBrightnessMethods"
# Get the CIM instance
$instance = Get-CimInstance -Namespace $namespaceName -ClassName $className
# Invoke the method with arguments
$methodArgs = @{
'Brightness' = $brightness # Desired brightness level
'Timeout' = 1 # The time period (in seconds) that the parameters should stay in effect.
}
Invoke-CimMethod -InputObject $instance -MethodName WmiSetBrightness -Arguments $methodArgs
}
function Toggle-Brightness {
# Restore to original brightness
if ((Get-Brightness) -eq 0) {
if (Test-Path variable:Global:originalBrightness) {
Set-Brightness $Global:originalBrightness
} else {
# Exception case handling
Set-Brightness 10
}
# Set brightness to lowest
} else {
# Save the original brightness
$Global:originalBrightness = Get-Brightness
Set-Brightness 0
}
}
# Create a windows form
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Brightness Control'
$form.Size = New-Object System.Drawing.Size(0,0)
$form.MinimizeBox = $true
$form.WindowState = 'Minimized'
# Add Resize event to call the Toggle-Brightness function
$form.Add_Resize({
if ($form.WindowState -eq 'Normal') {
$form.WindowState = 'Minimized'
Toggle-Brightness
}
})
# Show the form
$form.ShowDialog()
'Launch the program
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "pwsh -WindowStyle Hidden -File 2_with_GUI_app_toggle.ps1", 0, False
Set WshShell = Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment