Skip to content

Commit

Permalink
keep notification unregistering handle
Browse files Browse the repository at this point in the history
  • Loading branch information
F0903 committed Sep 10, 2024
1 parent 118abc5 commit 4bffd73
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
const LOGGER: Logger = Logger::new("main", "autopower");

fn main() -> Result<()> {
LOGGER.debug("Starting...");
LOGGER.debug("Starting... (main)");
let mut args = std::env::args();
if let Some(cmd) = args.nth(1) {
match cmd.as_str() {
Expand Down
24 changes: 22 additions & 2 deletions src/services/power_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ use windows::{
Win32::{
Foundation::{CloseHandle, FALSE, HANDLE, NO_ERROR, TRUE},
System::{
Power::{self, POWERBROADCAST_SETTING, SYSTEM_POWER_CONDITION},
Power::{
self, RegisterPowerSettingNotification, POWERBROADCAST_SETTING,
SYSTEM_POWER_CONDITION,
},
Services::{
RegisterServiceCtrlHandlerExW, SetServiceStatus, SERVICE_ACCEPT_POWEREVENT,
SERVICE_ACCEPT_STOP, SERVICE_CONTROL_POWEREVENT, SERVICE_CONTROL_STOP,
Expand All @@ -22,7 +25,7 @@ use windows::{
SystemServices::GUID_ACDC_POWER_SOURCE,
Threading::{CreateEventW, SetEvent, WaitForSingleObject, INFINITE},
},
UI::WindowsAndMessaging::{PBT_APMPOWERSTATUSCHANGE, PBT_POWERSETTINGCHANGE},
UI::WindowsAndMessaging::{self, PBT_APMPOWERSTATUSCHANGE, PBT_POWERSETTINGCHANGE},
},
};

Expand Down Expand Up @@ -237,6 +240,20 @@ impl WindowsService for PowerService {
LOGGER.error(format!("Could not set service status!\n{}", e));
}

LOGGER.debug("Registering power setting notification handling...");
let mut power_notif_handle = match RegisterPowerSettingNotification(
HANDLE(me.status_handle.unwrap().0),
&GUID_ACDC_POWER_SOURCE,
WindowsAndMessaging::REGISTER_NOTIFICATION_FLAGS(1),
) {
Ok(x) => x,
Err(e) => {
let msg = format!("Could not register power settings notification!\n{}", e);
LOGGER.error(&msg);
panic!("{}", msg);
}
};

// Wait for exit.
WaitForSingleObject(me.stop_event.unwrap(), INFINITE);
LOGGER.debug("Stop event signaled. Cleaning up and terminating...");
Expand All @@ -247,6 +264,9 @@ impl WindowsService for PowerService {
}
me.proxy.as_mut().unwrap().terminate().ok();

use windows::core::Free;
power_notif_handle.free();

drop(Box::from_raw(me));
}

Expand Down

0 comments on commit 4bffd73

Please sign in to comment.