on plug
Posted: 25 Aug 2021, 10:45
Hi again, I want to create a script which runs when I plug my laptop charger. How exactly can I do that?
Let's help each other out
https://www.autohotkey.com/boards/
https://www.autohotkey.com/boards/viewtopic.php?f=82&t=94118
Code: Select all
#Requires AutoHotkey v2.0-beta.1
#SingleInstance Force
Persistent()
NumPut('Int64', 0x4B00E9D55D3E9A59, 'Int64', 0x486551FF34FFBDA6, GUID_ACDC_POWER_SOURCE := Buffer(16))
if !hPowerNotify := DllCall('RegisterPowerSettingNotification', 'Ptr', A_ScriptHwnd, 'Ptr', GUID_ACDC_POWER_SOURCE, 'UInt', 0, 'Ptr')
throw OSError(A_LastError, -1, 'RegisterPowerSettingNotification')
Sleep(1) ; a notification is always emitted immediately after registering for it for some reason. this prevents seeing it
OnMessage(0x218, WM_POWERBROADCAST)
WM_POWERBROADCAST(wParam, lParam, msg, hwnd) {
switch wParam
{
case 0x8013: ; PBT_POWERSETTINGCHANGE
switch NumGet(lParam, 20, 'UChar') ; POWERBROADCAST_SETTING.Data
{
case 0: ; charger plugged
; do what u want
case 1: ; on battery
case 2: ; on UPS
}
}
}
Code: Select all
#Requires AutoHotkey v1.1.33+
#SingleInstance Force
#Persistent
VarSetCapacity(GUID_ACDC_POWER_SOURCE, 16)
NumPut(0x486551FF34FFBDA6, NumPut(0x4B00E9D55D3E9A59, GUID_ACDC_POWER_SOURCE, "Int64"), "Int64")
if !hPowerNotify := DllCall("RegisterPowerSettingNotification", "Ptr", A_ScriptHwnd, "Ptr", &GUID_ACDC_POWER_SOURCE, "UInt", 0, "Ptr")
throw Exception(A_LastError, -1, "RegisterPowerSettingNotification")
Sleep 1 ; a notification is always emitted immediately after registering for it for some reason. this prevents seeing it
OnMessage(0x218, "WM_POWERBROADCAST")
WM_POWERBROADCAST(wParam, lParam, msg, hwnd) {
switch wParam
{
case 0x8013: ; PBT_POWERSETTINGCHANGE
switch NumGet(lParam+20, "UChar") ; POWERBROADCAST_SETTING.Data
{
case 0: ; charger plugged
; do what u want
case 1: ; on battery
case 2: ; on UPS
}
}
}
Code: Select all
- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
<Provider Name="PowerAlert Agent" />
<EventID Qualifiers="0">202</EventID>
<Version>0</Version>
<Level>3</Level>
<Task>0</Task>
<Opcode>0</Opcode>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2021-10-07T18:25:49.8409462Z" />
<EventRecordID>140344</EventRecordID>
<Correlation />
<Execution ProcessID="0" ThreadID="0" />
<Channel>Application</Channel>
<Computer>DESKTOP-F63S7HN</Computer>
<Security />
</System>
- <EventData>
<Data>Device 1: On Battery</Data>
</EventData>
</Event>