-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
405 lines (346 loc) · 15.8 KB
/
Copy pathProgram.cs
File metadata and controls
405 lines (346 loc) · 15.8 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
using System;
using System.Drawing;
using System.IO;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Windows.Devices.Enumeration;
using Microsoft.Win32;
namespace MagicKeyBattery;
static class Program
{
private static System.Windows.Forms.Timer? _timer;
private static NotifyIcon? _trayIcon;
private static ToolStripMenuItem? _batteryMenu;
// 内部設定値(レジストリ同期用)
private static int _intervalMinutes = 3;
private static int _notifyThreshold = 20;
private static string _language = "en"; // デフォルトは英語(Reddit想定)
private static bool _hasNotifiedLowBattery = false;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool DestroyIcon(IntPtr handle);
private static IntPtr _currentIconHandle = IntPtr.Zero;
private const string REG_RUN_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
private const string REG_APP_KEY = @"SOFTWARE\MagicKeyBattery\Settings";
private const string APP_NAME = "MagicKeyBattery";
// --- Win32 API 宣言 ---
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("hid.dll", SetLastError = true)]
private static extern bool HidD_GetInputReport(IntPtr HidDeviceObject, byte[] ReportBuffer, uint ReportBufferLength);
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint OPEN_EXISTING = 3;
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
// --- 多言語辞書 ---
private static readonly Dictionary<string, Dictionary<string, string>> LocalizedText = new()
{
["en"] = new()
{
["checking"] = "Checking connection...",
["not_connected"] = "Not Connected",
["click_retry"] = "Not Connected (Click to retry)",
["click_refresh"] = "Click to refresh now",
["open_settings"] = "⚙️ Settings...",
["exit_app"] = "❌ Exit Application",
["dialog_title"] = "MagicKeyBattery Settings",
["lbl_interval"] = "Update Interval (Min):",
["lbl_threshold"] = "Low Battery Notification (%):",
["lbl_hint"] = "*Set to 0 to disable notifications",
["chk_startup"] = "Run at Windows Startup",
["btn_save"] = "Save",
["notify_title"] = "Low Battery Warning",
["notify_body"] = "Magic Keyboard battery is below {0}% (Current: {1}%)"
},
["ja"] = new()
{
["checking"] = "接続確認中...",
["not_connected"] = "未接続",
["click_retry"] = "未接続 (クリックで再試行)",
["click_refresh"] = "クリックで今すぐ更新",
["open_settings"] = "⚙️ 設定を開く...",
["exit_app"] = "❌ アプリを終了",
["dialog_title"] = "MagicKeyBattery 設定",
["lbl_interval"] = "自動更新間隔 (分):",
["lbl_threshold"] = "低残量通知を行う基準 (%):",
["lbl_hint"] = "※0に設定すると通知オフになります",
["chk_startup"] = "Windows起動時に実行する",
["btn_save"] = "保存",
["notify_title"] = "バッテリー残量警告",
["notify_body"] = "Magic Keyboard の残量が {0}% 以下(現在: {1}%)になりました。"
}
};
private static string T(string key) => LocalizedText[_language].ContainsKey(key) ? LocalizedText[_language][key] : key;
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
// レジストリから保存された設定をロード
LoadSettings();
_trayIcon = new NotifyIcon();
_trayIcon.Text = $"Magic Keyboard: {T("checking")}";
_trayIcon.Icon = SystemIcons.Application;
BuildContextMenu();
_trayIcon.Visible = true;
_timer = new System.Windows.Forms.Timer();
_timer.Interval = _intervalMinutes * 60 * 1000;
_timer.Tick += async (s, e) => await UpdateBatteryLevelAsync();
_timer.Start();
_ = UpdateBatteryLevelAsync();
Application.Run();
}
private static void BuildContextMenu()
{
if (_trayIcon == null) return;
ContextMenuStrip contextMenu = new ContextMenuStrip();
string currentText = _batteryMenu?.Text ?? $"🔋 Magic Keyboard: {T("checking")}";
_batteryMenu = new ToolStripMenuItem(currentText, null, async (s, e) => {
await UpdateBatteryLevelAsync();
});
contextMenu.Items.Add(_batteryMenu);
contextMenu.Items.Add(new ToolStripSeparator());
contextMenu.Items.Add(T("open_settings"), null, (s, e) => {
ShowSettingsDialog();
});
contextMenu.Items.Add(new ToolStripSeparator());
contextMenu.Items.Add(T("exit_app"), null, (s, e) => {
_timer?.Stop();
_trayIcon.Visible = false;
if (_currentIconHandle != IntPtr.Zero) DestroyIcon(_currentIconHandle);
Application.Exit();
});
_trayIcon.ContextMenuStrip = contextMenu;
}
private static async Task UpdateBatteryLevelAsync()
{
try
{
string[] endpointProperties = { "System.Devices.Aep.ContainerId", "System.Devices.Aep.IsConnected" };
var endpoints = await DeviceInformation.FindAllAsync("", endpointProperties, DeviceInformationKind.AssociationEndpoint);
Guid? targetContainerId = null;
bool isConnected = false;
foreach (var ep in endpoints)
{
if (string.IsNullOrEmpty(ep.Name)) continue;
if (ep.Name.Contains("Magic Keyboard", StringComparison.OrdinalIgnoreCase))
{
if (ep.Properties.ContainsKey("System.Devices.Aep.ContainerId"))
{
targetContainerId = (Guid?)ep.Properties["System.Devices.Aep.ContainerId"];
isConnected = (bool?)ep.Properties["System.Devices.Aep.IsConnected"] ?? false;
break;
}
}
}
if (targetContainerId == null || !isConnected)
{
UpdateUI(0, false);
return;
}
string interfaceAqs = $"System.Devices.ContainerId:=\"{{{targetContainerId}}}\"";
var interfaces = await DeviceInformation.FindAllAsync(interfaceAqs, null, DeviceInformationKind.DeviceInterface);
foreach (var iface in interfaces)
{
if (iface.Id.Contains("hid", StringComparison.OrdinalIgnoreCase) && iface.Id.Contains("Col02", StringComparison.OrdinalIgnoreCase))
{
IntPtr handle = CreateFile(iface.Id, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (handle != INVALID_HANDLE_VALUE)
{
byte[] buffer = new byte[8];
buffer[0] = 0x90;
if (HidD_GetInputReport(handle, buffer, (uint)buffer.Length))
{
byte batteryLevel = buffer[2];
if (batteryLevel <= 100 && batteryLevel > 0)
{
UpdateUI(batteryLevel, true);
}
}
CloseHandle(handle);
break;
}
}
}
}
catch { }
}
private static void UpdateUI(byte level, bool connected)
{
if (_trayIcon == null || _batteryMenu == null) return;
if (!connected)
{
_trayIcon.Text = $"Magic Keyboard: {T("not_connected")}";
_batteryMenu.Text = $"📴 Magic Keyboard: {T("click_retry")}";
SetDynamicIcon(0, false);
_hasNotifiedLowBattery = false;
return;
}
_trayIcon.Text = $"Magic Keyboard: {level}%";
string emoji = level >= 50 ? "🔋" : (level >= 20 ? "🔋" : "🪫");
_batteryMenu.Text = $"{emoji} Magic Keyboard: {level}% ({T("click_refresh")})";
SetDynamicIcon(level, true);
if (_notifyThreshold > 0 && level <= _notifyThreshold)
{
if (!_hasNotifiedLowBattery)
{
_trayIcon.ShowBalloonTip(
5000,
T("notify_title"),
string.Format(T("notify_body"), _notifyThreshold, level),
ToolTipIcon.Warning
);
_hasNotifiedLowBattery = true;
}
}
else
{
_hasNotifiedLowBattery = false;
}
}
private static void SetDynamicIcon(byte level, bool connected)
{
if (_trayIcon == null) return;
using (Bitmap bmp = new Bitmap(16, 16))
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
g.Clear(Color.Transparent);
if (!connected)
{
using (Pen grayPen = new Pen(Color.FromArgb(120, 120, 120), 1))
using (Pen redPen = new Pen(Color.Crimson, 2))
{
g.DrawRectangle(grayPen, 1, 3, 11, 9);
g.DrawLine(redPen, 3, 3, 11, 11);
g.DrawLine(redPen, 11, 3, 3, 11);
}
}
else
{
Color statusColor = level >= 50 ? Color.LimeGreen : (level >= 20 ? Color.Orange : Color.Crimson);
using (Pen framePen = new Pen(statusColor, 1))
using (Brush solidBrush = new SolidBrush(statusColor))
{
g.DrawRectangle(framePen, 0, 3, 12, 9);
g.FillRectangle(solidBrush, 13, 6, 2, 4);
int barWidth = (int)Math.Max(1, Math.Round((level / 100.0) * 10.0));
if (barWidth > 10) barWidth = 10;
g.FillRectangle(solidBrush, 2, 5, barWidth, 6);
}
}
IntPtr hIcon = bmp.GetHicon();
_trayIcon.Icon = Icon.FromHandle(hIcon);
if (_currentIconHandle != IntPtr.Zero) DestroyIcon(_currentIconHandle);
_currentIconHandle = hIcon;
}
}
private static void ShowSettingsDialog()
{
Form configForm = new Form
{
Width = 340,
Height = 280,
Text = T("dialog_title"),
StartPosition = FormStartPosition.CenterScreen,
FormBorderStyle = FormBorderStyle.FixedDialog,
MaximizeBox = false,
MinimizeBox = false,
BackColor = Color.FromArgb(30, 30, 30),
ForeColor = Color.White
};
Label lblInterval = new Label { Text = T("lbl_interval"), Left = 20, Top = 20, Width = 150, ForeColor = Color.LightGray };
NumericUpDown numInterval = new NumericUpDown { Left = 180, Top = 18, Width = 80, Minimum = 1, Maximum = 60, Value = _intervalMinutes, BackColor = Color.FromArgb(50, 50, 50), ForeColor = Color.White };
Label lblThreshold = new Label { Text = T("lbl_threshold"), Left = 20, Top = 60, Width = 150, ForeColor = Color.LightGray };
NumericUpDown numThreshold = new NumericUpDown { Left = 180, Top = 58, Width = 80, Minimum = 0, Maximum = 100, Value = _notifyThreshold, BackColor = Color.FromArgb(50, 50, 50), ForeColor = Color.White };
Label lblHint = new Label { Text = T("lbl_hint"), Left = 20, Top = 85, Width = 280, Font = new Font(configForm.Font.FontFamily, 7.5f), ForeColor = Color.Gray };
Label lblLang = new Label { Text = "Language / 言語:", Left = 20, Top = 115, Width = 150, ForeColor = Color.LightGray };
ComboBox cmbLang = new ComboBox { Left = 180, Top = 112, Width = 80, DropDownStyle = ComboBoxStyle.DropDownList, BackColor = Color.FromArgb(50, 50, 50), ForeColor = Color.White };
cmbLang.Items.AddRange(new object[] { "en", "ja" });
cmbLang.SelectedItem = _language;
CheckBox chkStartup = new CheckBox { Text = T("chk_startup"), Left = 20, Top = 155, Width = 250, Checked = IsStartupEnabled(), ForeColor = Color.LightGray };
Button btnSave = new Button { Text = T("btn_save"), Left = 115, Top = 200, Width = 90, Height = 30, FlatStyle = FlatStyle.Flat, BackColor = Color.FromArgb(0, 122, 204), ForeColor = Color.White };
btnSave.FlatAppearance.BorderSize = 0;
// 💡 修正: イベントハンドラを async (s, e) => に変更し、内部の await を有効化
btnSave.Click += async (s, e) =>
{
_intervalMinutes = (int)numInterval.Value;
_notifyThreshold = (int)numThreshold.Value;
_language = cmbLang.SelectedItem?.ToString() ?? "en";
SaveSettings();
ToggleStartup(chkStartup.Checked);
if (_timer != null) _timer.Interval = _intervalMinutes * 60 * 1000;
BuildContextMenu();
await UpdateBatteryLevelAsync();
configForm.Close();
};
configForm.Controls.AddRange(new Control[] { lblInterval, numInterval, lblThreshold, numThreshold, lblHint, lblLang, cmbLang, chkStartup, btnSave });
configForm.ShowDialog();
}
private static void SaveSettings()
{
try
{
using (RegistryKey key = Registry.CurrentUser.CreateSubKey(REG_APP_KEY))
{
key.SetValue("IntervalMinutes", _intervalMinutes);
key.SetValue("NotifyThreshold", _notifyThreshold);
key.SetValue("Language", _language);
}
}
catch { }
}
private static void LoadSettings()
{
try
{
// 💡 RegistryKey を RegistryKey? (Null許容型) に修正
using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(REG_APP_KEY))
{
if (key != null)
{
// int キャストの末尾の「!」は値型に対して不要なため除去
_intervalMinutes = (int)key.GetValue("IntervalMinutes", 3);
_notifyThreshold = (int)key.GetValue("NotifyThreshold", 20);
_language = key.GetValue("Language", "en")?.ToString() ?? "en";
}
}
if (string.IsNullOrEmpty(_language))
{
string currentCulture = CultureInfo.CurrentCulture.Name.ToLower();
_language = currentCulture.StartsWith("ja") ? "ja" : "en";
}
}
catch
{
_language = "en";
}
}
private static void ToggleStartup(bool enable)
{
try
{
using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(REG_RUN_KEY, true))
{
if (key == null) return;
if (enable) key.SetValue(APP_NAME, Application.ExecutablePath);
else key.DeleteValue(APP_NAME, false);
}
}
catch { }
}
private static bool IsStartupEnabled()
{
try
{
// 💡 RegistryKey? で安全に受け、内部の null チェックと同期させます
using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(REG_RUN_KEY, false))
{
return key != null && key.GetValue(APP_NAME) != null;
}
}
catch { return false; }
}
}