-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
409 lines (349 loc) · 15.2 KB
/
Copy pathMainForm.cs
File metadata and controls
409 lines (349 loc) · 15.2 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
406
407
408
409
using Microsoft.Win32;
using System.Diagnostics;
using System.Threading;
namespace WinTombstone
{
public partial class MainForm : Form
{
private readonly CoreManager _core;
private const int HOTKEY_ID = 9000;
private DateTime _ignoreTimerUntil = DateTime.MinValue;
private Rectangle _dragBox;
private int _dragRowIndex = -1;
private int _timerBusy;
public MainForm()
{
InitializeComponent();
InitializeCustomIcon();
_core = new CoreManager();
InitGrid();
InitEvents();
ApplyLanguage(); // 应用语言
RegisterGlobalHotkey();
}
private void InitializeCustomIcon()
{
UpdateThemedIcon();
SystemEvents.UserPreferenceChanged += (s, e) =>
{
if (e.Category == UserPreferenceCategory.General)
{
BeginInvoke(new Action(UpdateThemedIcon));
}
};
}
private void UpdateThemedIcon()
{
bool isDark = IsSystemDarkMode();
Color iconColor = isDark ? Color.White : Color.Black;
using (Bitmap bmp = new Bitmap(32, 32))
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.Transparent);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
using (Font f = new Font("Segoe UI Emoji", 20, FontStyle.Bold))
using (Brush b = new SolidBrush(iconColor))
{
var size = g.MeasureString("❄", f);
g.DrawString("❄", f, b, (32 - size.Width) / 2, (32 - size.Height) / 2);
}
var oldIcon = this.Icon;
Icon newIcon = Icon.FromHandle(bmp.GetHicon());
this.Icon = newIcon;
notifyIcon1.Icon = newIcon;
if (oldIcon != null && oldIcon != newIcon) oldIcon.Dispose();
}
}
private bool IsSystemDarkMode()
{
try
{
const string keyName = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
object value = Registry.GetValue(keyName, "SystemUsesLightTheme", null);
if (value == null) value = Registry.GetValue(keyName, "AppsUseLightTheme", 1);
if (value is int intVal) return intVal == 0;
}
catch { }
return false;
}
private void InitGrid()
{
dgvList.AutoGenerateColumns = false;
dgvList.AllowUserToAddRows = false;
dgvList.AllowDrop = true;
// 列定义使用Name查找,Text在ApplyLanguage中设置
dgvList.Columns.Add(new DataGridViewTextBoxColumn { Name = "colName", DataPropertyName = "AppName", ReadOnly = true });
dgvList.Columns.Add(new DataGridViewCheckBoxColumn { Name = "colFrozen", DataPropertyName = "IsFrozen" });
dgvList.Columns.Add(new DataGridViewCheckBoxColumn { Name = "colAuto", DataPropertyName = "AutoFreeze" });
dgvList.Columns.Add(new DataGridViewTextBoxColumn { Name = "colTimeout", DataPropertyName = "TimeoutSeconds" });
var btnDel = new DataGridViewButtonColumn
{
Name = "colAction",
UseColumnTextForButtonValue = true
};
dgvList.Columns.Add(btnDel);
dgvList.DataSource = new BindingSource { DataSource = _core.Settings.Whitelist };
}
private void ApplyLanguage()
{
Text = Localization.Get("Title");
notifyIcon1.Text = Localization.Get("Title");
dgvList.Columns["colName"].HeaderText = Localization.Get("ColName");
dgvList.Columns["colFrozen"].HeaderText = Localization.Get("ColFrozen");
dgvList.Columns["colAuto"].HeaderText = Localization.Get("ColAuto");
dgvList.Columns["colTimeout"].HeaderText = Localization.Get("ColTimeout");
dgvList.Columns["colAction"].HeaderText = Localization.Get("ColAction");
(dgvList.Columns["colAction"] as DataGridViewButtonColumn).Text = Localization.Get("ActionDelete");
btnUnfreezeAll.Text = Localization.Get("UnfreezeAll");
btnHelp.Text = Localization.Get("Help");
btnSettings.Text = Localization.Get("Settings"); // 新增:设置按钮文本
settingsMenuItemMain.Text = Localization.Get("Settings");
settingsMenuItemTray.Text = Localization.Get("Settings");
exitMenuItem.Text = Localization.Get("Exit");
RefreshGrid(); // 刷新表格以更新按钮文本等
}
private void RegisterGlobalHotkey()
{
NativeHelper.UnregisterHotKey(this.Handle, HOTKEY_ID);
NativeHelper.RegisterHotKey(this.Handle, HOTKEY_ID, (uint)_core.Settings.HotkeyModifier, (uint)_core.Settings.HotkeyKey);
}
private void InitEvents()
{
_core.AppStateChanged += (app) =>
{
if (IsDisposed) return;
BeginInvoke(new Action(RefreshGrid));
};
dgvList.CellContentClick += DgvList_CellContentClick;
dgvList.CellValueChanged += (s, e) =>
{
if (e.RowIndex < 0) return;
// 获取当前变更的列名
string colName = dgvList.Columns[e.ColumnIndex].Name;
// 只有在修改“自动冻结(colAuto)”或“超时时间(colTimeout)”时才保存
if (colName == "colAuto" || colName == "colTimeout")
{
_core.SaveSettings();
}
};
dgvList.CurrentCellDirtyStateChanged += (s, e) =>
{
if (dgvList.IsCurrentCellDirty && dgvList.CurrentCell is DataGridViewCheckBoxCell)
dgvList.CommitEdit(DataGridViewDataErrorContexts.Commit);
};
dgvList.MouseMove += DgvList_MouseMove;
dgvList.MouseDown += DgvList_MouseDown;
dgvList.DragOver += (s, e) => e.Effect = DragDropEffects.Move;
dgvList.DragDrop += DgvList_DragDrop;
this.FormClosing += (s, e) => {
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
Hide();
// 隐藏时可以顺便触发一次保存,以防万一
_core.SaveSettings();
}
else
{
// 系统关机或任务管理器结束任务时的保存尝试
_core.SaveSettings(forceImmediate: true);
}
};
exitMenuItem.Click += (s, e) => {
_core.RestoreAll();
_core.SaveSettings(forceImmediate: true); // 强制立即保存
Application.Exit();
};
// 绑定设置菜单和按钮
settingsMenuItemMain.Click += OpenSettings;
settingsMenuItemTray.Click += OpenSettings;
btnSettings.Click += OpenSettings; // 新增:绑定主界面设置按钮
// 绑定说明按钮
btnHelp.Click += (s, e) => MessageBox.Show(Localization.Get("HelpContent"), Localization.Get("HelpTitle"), MessageBoxButtons.OK, MessageBoxIcon.Information);
notifyIcon1.MouseClick += (s, e) => {
if (e.Button == MouseButtons.Left) { Show(); WindowState = FormWindowState.Normal; Activate(); }
};
btnUnfreezeAll.Click += (s, e) => {
SetFreezeCooldown(2);
_core.RestoreAll();
RefreshGrid();
_core.SaveSettings();
notifyIcon1.ShowBalloonTip(2000, Localization.Get("MsgOpDone"), Localization.Get("MsgAllRestored"), ToolTipIcon.Info);
};
}
private void OpenSettings(object sender, EventArgs e)
{
using (var settingsForm = new SettingsForm(_core))
{
if (settingsForm.ShowDialog() == DialogResult.OK)
{
// 重新注册热键
RegisterGlobalHotkey();
// 如果语言改变,刷新UI
if (settingsForm.LanguageChanged)
{
ApplyLanguage();
}
}
}
}
private void DgvList_MouseDown(object sender, MouseEventArgs e)
{
_dragRowIndex = dgvList.HitTest(e.X, e.Y).RowIndex;
if (_dragRowIndex != -1)
{
Size dragSize = SystemInformation.DragSize;
_dragBox = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
}
else _dragBox = Rectangle.Empty;
}
private void DgvList_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
if (_dragBox != Rectangle.Empty && !_dragBox.Contains(e.X, e.Y))
dgvList.DoDragDrop(dgvList.Rows[_dragRowIndex], DragDropEffects.Move);
}
}
private void DgvList_DragDrop(object sender, DragEventArgs e)
{
Point clientPoint = dgvList.PointToClient(new Point(e.X, e.Y));
int targetRowIndex = dgvList.HitTest(clientPoint.X, clientPoint.Y).RowIndex;
if (targetRowIndex != -1 && _dragRowIndex != -1 && _dragRowIndex != targetRowIndex)
{
var list = _core.Settings.Whitelist;
var item = list[_dragRowIndex];
list.RemoveAt(_dragRowIndex);
list.Insert(targetRowIndex, item);
RefreshGrid();
_core.SaveSettings();
}
}
private void DgvList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return;
var app = _core.Settings.Whitelist[e.RowIndex];
if (dgvList.Columns[e.ColumnIndex].Name == "colAction")
{
if (app.IsFrozen) _core.UnfreezeApp(app);
_core.Settings.Whitelist.RemoveAt(e.RowIndex);
RefreshGrid();
_core.SaveSettings();
}
else if (dgvList.Columns[e.ColumnIndex].Name == "colFrozen")
{
dgvList.CommitEdit(DataGridViewDataErrorContexts.Commit);
SetFreezeCooldown(2);
if (app.IsFrozen) _core.FreezeApp(app);
else _core.UnfreezeApp(app);
}
}
private void RefreshGrid()
{
if (dgvList.IsCurrentCellInEditMode) return;
(dgvList.DataSource as BindingSource)?.ResetBindings(false);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312 && m.WParam.ToInt32() == HOTKEY_ID)
{
AddNewAppAndFreezeFromForeground();
}
base.WndProc(ref m);
}
private void SetFreezeCooldown(double seconds) => _ignoreTimerUntil = DateTime.Now.AddSeconds(seconds);
private void AddNewAppAndFreezeFromForeground()
{
IntPtr hWnd = NativeHelper.GetForegroundWindow();
if (hWnd == IntPtr.Zero) return;
NativeHelper.GetWindowThreadProcessId(hWnd, out uint pid);
// 修复:使用 NativeHelper 获取路径,避免因权限问题导致 MainModule 抛出异常
string path = NativeHelper.GetRealProcessPath((int)pid);
if (string.IsNullOrEmpty(path))
{
// 如果实在获取不到路径,可以在这里记录日志或者播放错误提示音
System.Diagnostics.Debug.WriteLine($"[Error] 无法获取进程路径, PID: {pid}");
return;
}
// 检查黑名单
if (_core.IsBlacklisted(path))
{
Console.WriteLine($"[Core] 跳过黑名单应用: {path}");
return;
}
SetFreezeCooldown(2.0);
var targetApp = _core.Settings.Whitelist.FirstOrDefault(a => a.ExePath.Equals(path, StringComparison.OrdinalIgnoreCase));
if (targetApp == null)
{
targetApp = new TargetApp
{
AppName = Path.GetFileNameWithoutExtension(path),
ExePath = path,
LastActiveTime = DateTime.Now,
TimeoutSeconds = 30
};
_core.Settings.Whitelist.Add(targetApp);
_core.SaveSettings();
RefreshGrid();
_core.FreezeApp(targetApp);
notifyIcon1.ShowBalloonTip(1000, Localization.Get("MsgAddSuccess"), $"{targetApp.AppName} " + Localization.Get("MsgFrozen"), ToolTipIcon.Info);
}
else if (!targetApp.IsFrozen)
{
_core.FreezeApp(targetApp);
}
}
private async void timerCheck_Tick(object sender, EventArgs e)
{
if (DateTime.Now < _ignoreTimerUntil) return;
if (Interlocked.CompareExchange(ref _timerBusy, 1, 0) != 0) return;
try
{
IntPtr fgWin = NativeHelper.GetForegroundWindow();
string fgPath = null;
if (fgWin != IntPtr.Zero)
{
NativeHelper.GetWindowThreadProcessId(fgWin, out uint fgPid);
fgPath = NativeHelper.GetRealProcessPath((int)fgPid);
}
TargetApp toUnfreeze = null;
TargetApp toFreeze = null;
foreach (var app in _core.Settings.Whitelist)
{
bool isForeground = fgPath != null &&
string.Equals(app.ExePath, fgPath, StringComparison.OrdinalIgnoreCase);
if (isForeground)
{
app.LastActiveTime = DateTime.Now;
if (app.IsFrozen && NativeHelper.IsWindowVisible(fgWin))
toUnfreeze = app;
}
else
{
if (app.AutoFreeze && !app.IsFrozen)
{
if ((DateTime.Now - app.LastActiveTime).TotalSeconds > app.TimeoutSeconds)
{
SetFreezeCooldown(1.0);
toFreeze = app;
}
}
}
}
if (toUnfreeze != null)
{
await Task.Run(() => _core.UnfreezeApp(toUnfreeze));
}
else if (toFreeze != null)
{
await Task.Run(() => _core.FreezeApp(toFreeze));
}
}
finally
{
Interlocked.Exchange(ref _timerBusy, 0);
}
}
}
}