-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoreManager.cs
More file actions
646 lines (561 loc) · 21.5 KB
/
Copy pathCoreManager.cs
File metadata and controls
646 lines (561 loc) · 21.5 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading;
namespace WinTombstone
{
public class CoreManager
{
public AppSettings Settings { get; private set; }
private readonly string _jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json");
private readonly object _settingsLock = new object();
private readonly Dictionary<string, List<OverlayForm>> _activeOverlays = new Dictionary<string, List<OverlayForm>>();
private readonly Dictionary<int, IntPtr> _frozenJobs = new Dictionary<int, IntPtr>();
private readonly object _overlayLock = new object();
private CancellationTokenSource _saveCts;
private SynchronizationContext _uiContext;
public static readonly List<string> SystemBlacklist = new List<string>
{
"explorer.exe",
"taskmgr.exe",
"wintombstone.exe",
"searchui.exe",
"searchapp.exe",
"shellexperiencehost.exe",
"lockapp.exe"
};
public event Action<TargetApp> AppStateChanged;
public CoreManager()
{
_uiContext = SynchronizationContext.Current;
NativeHelper.EnableDebugPrivilege();
LoadSettings();
}
// ... LoadSettings 和 SaveSettings 方法保持不变,无需修改 ...
public void LoadSettings()
{
lock (_settingsLock)
{
if (File.Exists(_jsonPath))
{
try
{
string json = File.ReadAllText(_jsonPath);
Settings = JsonSerializer.Deserialize<AppSettings>(json) ?? new AppSettings();
}
catch { Settings = new AppSettings(); }
}
else
{
Settings = new AppSettings();
}
if (string.IsNullOrEmpty(Settings.Language)) Settings.Language = "CN";
Localization.CurrentLanguage = Settings.Language;
if (Settings.Blacklist == null) Settings.Blacklist = new List<string>();
if (Settings.LinkedApps == null) Settings.LinkedApps = new Dictionary<string, List<string>>();
if (Settings.Whitelist != null)
{
foreach (var app in Settings.Whitelist)
{
app.IsFrozen = CheckIfAppIsActuallySuspended(app);
}
}
}
}
public void SaveSettings(bool forceImmediate = false)
{
if (!forceImmediate)
{
_saveCts?.Cancel();
_saveCts = new CancellationTokenSource();
}
var token = _saveCts?.Token ?? CancellationToken.None;
Task.Run(async () =>
{
try
{
if (!forceImmediate)
{
await Task.Delay(500, token);
if (token.IsCancellationRequested) return;
}
string json;
lock (_settingsLock)
{
Settings.Language = Localization.CurrentLanguage;
json = JsonSerializer.Serialize(Settings, new JsonSerializerOptions { WriteIndented = true });
}
string tempPath = _jsonPath + ".tmp";
await File.WriteAllTextAsync(tempPath, json, CancellationToken.None);
if (File.Exists(_jsonPath)) File.Delete(_jsonPath);
File.Move(tempPath, _jsonPath);
}
catch { }
});
}
// ... (End of unmodified section) ...
private bool CheckIfAppIsActuallySuspended(TargetApp app)
{
try
{
var processes = GetProcessesByPath(app.ExePath);
if (processes.Count == 0) return false;
try
{
foreach (var p in processes)
{
if (IsProcessSuspended(p)) return true;
}
}
finally
{
foreach (var p in processes) { try { p.Dispose(); } catch { } }
}
}
catch { }
return false;
}
public bool IsBlacklisted(string exeName)
{
string name = Path.GetFileName(exeName).ToLower();
if (SystemBlacklist.Contains(name)) return true;
if (Settings.Blacklist.Any(b => b.Equals(name, StringComparison.OrdinalIgnoreCase))) return true;
return false;
}
public void FreezeApp(TargetApp app)
{
Console.WriteLine($"[Core] 尝试冻结: {app.AppName}");
if (IsBlacklisted(app.ExePath) || IsBlacklisted(app.AppName + ".exe"))
{
UnfreezeApp(app);
return;
}
lock (_overlayLock)
{
if (_activeOverlays.ContainsKey(app.ExePath)) return;
}
List<Process> processes = null;
try
{
processes = GetProcessesByPath(app.ExePath);
if (processes.Count == 0)
{
app.LastActiveTime = DateTime.Now;
UpdateAppState(app, false);
return;
}
if (processes.Any(p => IsProcessSuspended(p)))
{
Console.WriteLine($"[Core] 检测到 {app.AppName} 已处于被挂起状态,同步状态。");
UpdateAppState(app, true);
return;
}
List<OverlayForm> overlays = null;
_uiContext.Send(_ =>
{
overlays = GenerateOverlaysForProcesses(app, processes);
}, null);
if (overlays != null && overlays.Count > 0)
{
lock (_overlayLock)
{
_activeOverlays[app.ExePath] = overlays;
}
}
foreach (var p in processes)
{
SuspendSingleProcess(p);
}
_uiContext.Send(_ => NativeHelper.ForceReleaseMouse(), null);
ProcessLinkedApps(app.ExePath, isSuspending: true);
UpdateAppState(app, true);
}
catch (Exception ex)
{
Console.WriteLine($"[Core] 冻结流程失败: {ex.Message}");
UnfreezeApp(app);
}
finally
{
if (processes != null)
foreach (var p in processes) { try { p.Dispose(); } catch { } }
}
}
public void UnfreezeApp(TargetApp app)
{
Console.WriteLine($"[Core] 尝试解冻: {app.AppName}");
List<Process> processes = null;
try
{
processes = GetProcessesByPath(app.ExePath);
foreach (var p in processes)
{
ResumeSingleProcess(p);
}
ProcessLinkedApps(app.ExePath, isSuspending: false);
List<OverlayForm> overlays = null;
lock (_overlayLock)
{
_activeOverlays.TryGetValue(app.ExePath, out overlays);
if (overlays != null) _activeOverlays.Remove(app.ExePath);
}
if (overlays != null)
{
_uiContext.Send(_ =>
{
foreach (var overlay in overlays)
{
RestoreOriginalWindow(overlay);
}
}, null);
}
app.LastActiveTime = DateTime.Now;
UpdateAppState(app, false);
}
catch (Exception ex)
{
Console.WriteLine($"[Core] 解冻流程异常: {ex.Message}");
}
finally
{
if (processes != null)
foreach (var p in processes) { try { p.Dispose(); } catch { } }
}
}
// ================= JOB OBJECT 冻结机制 =================
private void FreezeProcessWithJobObject(int pid)
{
if (_frozenJobs.ContainsKey(pid))
{
Console.WriteLine($"[Core] PID {pid} already frozen, skipping");
return;
}
IntPtr hProcess = NativeHelper.OpenProcess(NativeHelper.PROCESS_ALL_ACCESS, false, pid);
if (hProcess == IntPtr.Zero)
{
Console.WriteLine($"[Core] OpenProcess failed PID {pid}, Error: {Marshal.GetLastWin32Error()}");
return;
}
IntPtr hJob = NativeHelper.CreateJobObjectW(IntPtr.Zero, null);
if (hJob == IntPtr.Zero)
{
int err = Marshal.GetLastWin32Error();
NativeHelper.CloseHandle(hProcess);
Console.WriteLine($"[Core] CreateJobObject failed, Error: {err}");
return;
}
if (!NativeHelper.AssignProcessToJobObject(hJob, hProcess))
{
int err = Marshal.GetLastWin32Error();
NativeHelper.CloseHandle(hJob);
NativeHelper.CloseHandle(hProcess);
Console.WriteLine($"[Core] AssignProcessToJobObject failed PID {pid}, Error: {err}");
return;
}
NativeHelper.CloseHandle(hProcess);
if (!NativeHelper.JobFreeze(hJob, true))
{
int err = Marshal.GetLastWin32Error();
NativeHelper.CloseHandle(hJob);
Console.WriteLine($"[Core] JobFreeze failed PID {pid}, Error: {err}");
return;
}
_frozenJobs[pid] = hJob;
Console.WriteLine($"[Core] PID {pid} frozen via Job Object");
}
private void UnfreezeProcessWithJobObject(int pid)
{
if (!_frozenJobs.TryGetValue(pid, out IntPtr hJob))
{
return;
}
NativeHelper.JobFreeze(hJob, false);
NativeHelper.CloseHandle(hJob);
_frozenJobs.Remove(pid);
Console.WriteLine($"[Core] PID {pid} unfrozen");
}
private void SuspendSingleProcess(Process p)
{
try
{
if (p.HasExited) return;
FreezeProcessWithJobObject(p.Id);
}
catch (Exception ex)
{
Console.WriteLine($"[Core] freeze PID {p.Id} exception: {ex.Message}");
}
}
private void ResumeSingleProcess(Process p)
{
try
{
if (p.HasExited) return;
UnfreezeProcessWithJobObject(p.Id);
}
catch (Exception ex)
{
Console.WriteLine($"[Core] unfreeze PID {p.Id} exception: {ex.Message}");
}
}
public void RestoreAll()
{
if (Settings?.Whitelist == null) return;
foreach (var app in Settings.Whitelist.Where(a => a.IsFrozen).ToList())
{
UnfreezeApp(app);
}
foreach (var kvp in _frozenJobs.ToList())
{
NativeHelper.JobFreeze(kvp.Value, false);
NativeHelper.CloseHandle(kvp.Value);
}
_frozenJobs.Clear();
lock (_overlayLock)
{
_activeOverlays.Clear();
}
}
// ... 后续代码 (GenerateOverlaysForProcesses, CreateOverlayForWindow, RestoreOriginalWindow,
// IsProcessAliveSafe, GetProcessesByPath 等) 保持原样,直接复制粘贴原来的即可 ...
// 为了确保完整性,以下是需要保留的关键辅助函数(请确保您没有删除它们)
private List<OverlayForm> GenerateOverlaysForProcesses(TargetApp app, List<Process> processes)
{
var overlays = new List<OverlayForm>();
foreach (var p in processes)
{
try
{
if (p.HasExited) continue;
var windows = NativeHelper.GetVisibleWindowsForProcess(p.Id);
foreach (var hWnd in windows)
{
if (!NativeHelper.IsTaskbarWindow(hWnd)) continue;
NativeHelper.RECT rect;
bool isMinimized = NativeHelper.IsIconic(hWnd);
if (isMinimized)
{
NativeHelper.WINDOWPLACEMENT placement = new NativeHelper.WINDOWPLACEMENT();
placement.length = Marshal.SizeOf(placement);
NativeHelper.GetWindowPlacement(hWnd, ref placement);
rect = placement.rcNormalPosition;
}
else
{
NativeHelper.GetWindowRect(hWnd, out rect);
}
if (rect.Width <= 0 || rect.Height <= 0) continue;
var overlay = CreateOverlayForWindow(app, hWnd, rect, isMinimized);
if (overlay != null) overlays.Add(overlay);
}
}
catch { }
}
return overlays;
}
private OverlayForm CreateOverlayForWindow(TargetApp app, IntPtr hWnd, NativeHelper.RECT rect, bool isMinimized)
{
IntPtr hPrev = NativeHelper.GetWindow(hWnd, NativeHelper.GW_HWNDPREV);
Bitmap bmp = new Bitmap(rect.Width, rect.Height);
if (!isMinimized)
{
using (Graphics g = Graphics.FromImage(bmp))
{
IntPtr hdc = g.GetHdc();
try
{
if (!NativeHelper.PrintWindow(hWnd, hdc, NativeHelper.PW_RENDERFULLCONTENT))
NativeHelper.PrintWindow(hWnd, hdc, 0);
}
finally { g.ReleaseHdc(hdc); }
}
}
NativeHelper.ShowWindow(hWnd, NativeHelper.SW_HIDE);
var overlay = new OverlayForm(app, bmp, hWnd, UnfreezeApp, () => SaveSettings())
{
Location = new Point(rect.Left, rect.Top),
Size = new Size(rect.Width, rect.Height),
StartPosition = FormStartPosition.Manual
};
if (isMinimized)
{
overlay.WindowState = FormWindowState.Minimized;
}
overlay.Show();
if (hPrev != IntPtr.Zero && !isMinimized)
{
NativeHelper.SetWindowPos(overlay.Handle, hPrev, 0, 0, 0, 0,
NativeHelper.SWP_NOMOVE | NativeHelper.SWP_NOSIZE | NativeHelper.SWP_NOACTIVATE);
}
return overlay;
}
private void RestoreOriginalWindow(OverlayForm overlay)
{
try
{
IntPtr originalHwnd = overlay.OriginalWindowHandle;
bool isOverlayMinimized = overlay.WindowState == FormWindowState.Minimized;
NativeHelper.ShowWindow(originalHwnd, NativeHelper.SW_SHOW);
if (NativeHelper.IsIconic(originalHwnd) || isOverlayMinimized)
{
NativeHelper.ShowWindow(originalHwnd, NativeHelper.SW_RESTORE);
NativeHelper.SetForegroundWindow(originalHwnd);
}
else
{
NativeHelper.SetWindowPos(originalHwnd, IntPtr.Zero,
overlay.Location.X, overlay.Location.Y, 0, 0,
NativeHelper.SWP_NOSIZE | NativeHelper.SWP_NOZORDER | NativeHelper.SWP_SHOWWINDOW | NativeHelper.SWP_NOACTIVATE);
}
overlay.Close();
}
catch { }
}
private void UpdateAppState(TargetApp app, bool isFrozen)
{
app.IsFrozen = isFrozen;
AppStateChanged?.Invoke(app);
}
private List<Process> GetProcessesByPath(string exePath)
{
var result = new List<Process>();
if (string.IsNullOrWhiteSpace(exePath)) return result;
string targetName = Path.GetFileNameWithoutExtension(exePath);
var candidates = Process.GetProcessesByName(targetName).ToList();
if (candidates.Count == 0)
{
try { candidates.AddRange(Process.GetProcesses()); } catch { }
}
var distinctCandidates = candidates.GroupBy(p => p.Id).Select(g => g.First()).ToList();
var matchedPids = new HashSet<int>();
foreach (var p in distinctCandidates)
{
try
{
if (!IsProcessAliveSafe(p)) continue;
string currentPath = NativeHelper.GetRealProcessPath(p.Id);
if (!string.IsNullOrEmpty(currentPath) &&
string.Equals(currentPath, exePath, StringComparison.OrdinalIgnoreCase))
{
matchedPids.Add(p.Id);
}
}
catch { }
}
foreach (var p in distinctCandidates)
{
try { p.Dispose(); } catch { }
}
if (matchedPids.Count == 0) return result;
var parentChildMap = NativeHelper.GetProcessParentChildrenMap();
var pidsToProcess = new Queue<int>(matchedPids);
var allPids = new HashSet<int>(matchedPids);
while (pidsToProcess.Count > 0)
{
int currentPid = pidsToProcess.Dequeue();
if (parentChildMap.TryGetValue(currentPid, out var children))
{
foreach (var childId in children)
{
if (allPids.Add(childId)) pidsToProcess.Enqueue(childId);
}
}
}
var finalResult = new List<Process>();
foreach (var pid in allPids)
{
try
{
var p = Process.GetProcessById(pid);
if (IsProcessAliveSafe(p))
{
finalResult.Add(p);
}
else
{
try { p.Dispose(); } catch { }
}
}
catch { }
}
return finalResult;
}
private bool IsProcessAliveSafe(Process p)
{
try
{
return !p.HasExited;
}
catch (System.ComponentModel.Win32Exception)
{
return IsProcessRunningViaNative(p.Id);
}
catch
{
return false;
}
}
private bool IsProcessRunningViaNative(int pid)
{
IntPtr hProcess = IntPtr.Zero;
try
{
hProcess = NativeHelper.OpenProcess(NativeHelper.PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
if (hProcess != IntPtr.Zero) return true;
}
catch { }
finally
{
if (hProcess != IntPtr.Zero) NativeHelper.CloseHandle(hProcess);
}
return false;
}
private string GetSafeProcessPath(int pid)
{
return NativeHelper.GetRealProcessPath(pid);
}
private bool IsProcessSuspended(Process process)
{
try
{
process.Refresh();
foreach (ProcessThread thread in process.Threads)
{
if (thread.ThreadState == System.Diagnostics.ThreadState.Wait &&
thread.WaitReason == ThreadWaitReason.Suspended)
{
return true;
}
}
}
catch
{
return false;
}
return false;
}
private void ProcessLinkedApps(string mainExePath, bool isSuspending)
{
if (Settings.LinkedApps == null) return;
string mainExeName = Path.GetFileName(mainExePath).ToLower();
if (!Settings.LinkedApps.ContainsKey(mainExeName)) return;
var linkedList = Settings.LinkedApps[mainExeName];
foreach (var linkedExe in linkedList)
{
if (string.IsNullOrWhiteSpace(linkedExe) || IsBlacklisted(linkedExe)) continue;
string nameNoExt = Path.GetFileNameWithoutExtension(linkedExe);
try
{
var processes = Process.GetProcessesByName(nameNoExt);
foreach (var p in processes)
{
if (isSuspending) SuspendSingleProcess(p);
else ResumeSingleProcess(p);
}
}
catch { }
}
}
}
}