Created
July 26, 2023 19:07
-
-
Save WingTillDie/5b8471e6eb0594e9b8f3a8deae8cee66 to your computer and use it in GitHub Desktop.
Toggle Screen Brightness via an icon in System Tray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Right click to dispose | |
# 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 { | |
# If brightness is not at the lowest, set to lowest, otherwise set to original | |
if ((Get-Brightness) -eq 0) { | |
#Set-Brightness $originalBrightness | |
Set-Brightness $Global:originalBrightness | |
} else { | |
# Save the original brightness | |
#$originalBrightness = Get-Brightness | |
$Global:originalBrightness = Get-Brightness | |
Set-Brightness 0 | |
} | |
} | |
# Create notify icon object | |
$notifyIcon = New-Object System.Windows.Forms.NotifyIcon | |
#$notifyIcon.Icon = $iconPath | |
$notifyIcon.Icon = [System.Drawing.SystemIcons]::Information | |
$notifyIcon.Text = "Toggle Brightness" | |
$notifyIcon.Visible = $true | |
# Add click event to notify icon | |
$notifyIcon.add_MouseClick({ | |
param($sender, $e) | |
if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Left) { | |
Toggle-Brightness | |
} elseif ($e.Button -eq [System.Windows.Forms.MouseButtons]::Right) { | |
$notifyIcon.Dispose() | |
} | |
}) | |
# Prevent PowerShell from closing and removing the icon | |
# Replace with your own condition to exit when appropriate. | |
while ($true) { Start-Sleep -Seconds 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment