If you are building desktop utilities, monitoring hardware power states is a standard requirement. In this technical guide, we'll look at the native code interfaces for query and notification of AC power status in C++ (Windows) and Swift (macOS).

Windows: The GetSystemPowerStatus API

To poll the power state on Windows, we use the classic Win32 API function GetSystemPowerStatus. It fills a structure containing details about AC power status, battery charge percentage, and battery life remaining.

#include <windows.h>
#include <iostream>

void CheckPower() {
    SYSTEM_POWER_STATUS status;
    if (GetSystemPowerStatus(&status)) {
        if (status.ACLineStatus == 1) {
            std::cout << "AC power is connected." << std::endl;
        } else if (status.ACLineStatus == 0) {
            std::cout << "Running on battery." << std::endl;
        } else {
            std::cout << "Power status unknown." << std::endl;
        }
    }
}

macOS: The IOPowerSources Framework

Under macOS, the IOKit library handles hardware events. We can fetch current charging information using IOPSCopyPowerSourcesInfo and extract details with Swift helper functions.

import Foundation
import IOKit.ps

func isACConnected() -> Bool {
    let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()
    let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array
    
    for source in sources {
        if let description = IOPSGetPowerSourceDescription(snapshot, source).takeUnretainedValue() as? [String: Any] {
            if let powerSourceState = description[kIOPSPowerSourceStateKey] as? String {
                return powerSourceState == kIOPSACPowerValue
            }
        }
    }
    return false
}

Conclusion

Integrating these systems requires carefully handling OS-specific message queues and thread safety to avoid blocking the main UI thread. Charger Removal Alarm wraps these natively for maximum performance.

Ready to protect your charger?

Join thousands of users who never forget their chargers anymore

Download Now