-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpowermonitor.cpp
82 lines (62 loc) · 2.32 KB
/
powermonitor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "powermonitor.h"
#include <Windows.h>
#include <QMessageBox>
#include <QDebug>
#pragma comment(lib, "user32.lib")
_SYSTEM_POWER_STATUS PowerMonitor::powerStatus;
PowerMonitor::PowerMonitor(QWidget *parent ):QWidget(parent)
{
hPowerSourceNotify = RegisterPowerSettingNotification((HWND)this->winId(), &GUID_ACDC_POWER_SOURCE, DEVICE_NOTIFY_WINDOW_HANDLE);
hPowerPercentageNotify = RegisterPowerSettingNotification((HWND)this->winId(), &GUID_BATTERY_PERCENTAGE_REMAINING, DEVICE_NOTIFY_WINDOW_HANDLE);
if (!GetSystemPowerStatus(&powerStatus) && setting.value("tray/showBattery").toBool()){
QMessageBox msgBox(QMessageBox::Critical, "Error", "Error get system power status.");
msgBox.exec();
}
updateTimer = new QTimer(this);
QObject::connect(updateTimer, &QTimer::timeout, this, &PowerMonitor::RoutineUpdate );
updateTimer -> start(period*1000);
}
// used in update timer
void PowerMonitor::RoutineUpdate(){
if (!updatedRecently){
UpdateOnce();
}
updatedRecently = false;
return;
}
bool PowerMonitor::nativeEvent(const QByteArray & , void * message, long * result) {
MSG *msg = static_cast<MSG*>(message);
if (msg->message == WM_POWERBROADCAST) {
if (msg->wParam == PBT_POWERSETTINGCHANGE) {
POWERBROADCAST_SETTING *p = (POWERBROADCAST_SETTING *)msg->lParam;
GUID guid = p->PowerSetting;
if (guid == GUID_ACDC_POWER_SOURCE) {
//qDebug() << "Power source change!";
UpdateOnce();
}
else if (guid == GUID_BATTERY_PERCENTAGE_REMAINING){
//qDebug() << "Remaining percentage change!";
UpdateOnce();
}
}
*result = true;
return true;
}
return false;
}
bool PowerMonitor::UpdateOnce(){
updatedRecently = true;
bool result = GetSystemPowerStatus(&powerStatus);
qDebug() << "Power monitor updated";
emit powerStatusUpdated(powerStatus);
return result;
}
_SYSTEM_POWER_STATUS PowerMonitor::getPowerStatus(){return powerStatus;}
bool PowerMonitor::isOnAC(){
return (bool)powerStatus.ACLineStatus;
}
PowerMonitor::~PowerMonitor(){
delete updateTimer;
UnregisterPowerSettingNotification(hPowerSourceNotify);
UnregisterPowerSettingNotification(hPowerPercentageNotify);
}