Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
791 lines (714 loc) · 29.7 KB
/
Copy pathProgram.cs
File metadata and controls
791 lines (714 loc) · 29.7 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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace AfterCtrlC;
internal static class Program
{
public const string AppName = "AfterCtrlC";
private const string MutexName = @"Global\AfterCtrlC.SingleInstance";
private const string ShowEventName = @"Local\AfterCtrlC.ShowSettings";
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
/// <summary>
/// Windows Forms, the single-file bundle, and the Win32 marshalling layer
/// all need a writable temp directory. When the inherited one is locked
/// down, redirect TEMP to a folder beside the executable so the app can
/// still start instead of failing at the first native call.
/// </summary>
private static void EnsureWritableTemp()
{
try
{
var current = Path.GetTempPath();
if (Directory.Exists(current))
{
var probe = Path.Combine(current, ".dshcf-" + Guid.NewGuid().ToString("N")[..6]);
File.WriteAllText(probe, "x");
File.Delete(probe);
return;
}
}
catch
{
// Not writable: fall through to the redirect.
}
foreach (var candidate in new[]
{
Path.Combine(AppContext.BaseDirectory, "tmp"),
Path.Combine(Path.GetPathRoot(AppContext.BaseDirectory) ?? "C:\\", "AfterCtrlC-tmp"),
})
{
try
{
Directory.CreateDirectory(candidate);
var probe = Path.Combine(candidate, ".dshcf-probe");
File.WriteAllText(probe, "x");
File.Delete(probe);
Environment.SetEnvironmentVariable("TMP", candidate);
Environment.SetEnvironmentVariable("TEMP", candidate);
Environment.SetEnvironmentVariable("TMPDIR", candidate);
return;
}
catch
{
// Try the next candidate.
}
}
}
/// <summary>
/// A WinExe has no console, so give the command-line modes one when they
/// are launched from a terminal. Without this the output would vanish.
/// </summary>
private static void EnsureConsole()
{
// The Chinese strings must survive the console code page.
try { Console.OutputEncoding = new UTF8Encoding(false); } catch { }
if (!AttachConsole(ATTACH_PARENT_PROCESS)) return;
var stdout = Console.OpenStandardOutput();
var writer = new StreamWriter(stdout, new UTF8Encoding(false)) { AutoFlush = true };
Console.SetOut(writer);
Console.SetError(writer);
}
[STAThread]
private static void Main(string[] args)
{
EnsureWritableTemp();
// Command-line modes run before the single-instance guard: they are
// diagnostics and must work even while the tray app is running.
if (HandleCli(args)) return;
// Only one detector may run; a second launch just opens the settings.
using var mutex = new Mutex(initiallyOwned: true, MutexName, out var isFirst);
if (!isFirst)
{
SignalExistingInstance();
return;
}
ApplicationConfiguration.Initialize();
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += (_, e) => SettingsStore.Log("unhandled: " + e.Exception);
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
SettingsStore.Log("fatal: " + e.ExceptionObject);
if (!TryStartAutostartWatch())
{
// Nothing to do; the thread below owns the message loop.
}
var context = new TrayApplication();
App.Current = context;
Application.Run(context);
GC.KeepAlive(mutex);
}
private static bool TryStartAutostartWatch() => true;
/// <summary>Wake an already-running instance instead of starting a second one.</summary>
private static void SignalExistingInstance()
{
try
{
if (EventWaitHandle.TryOpenExisting(ShowEventName, out var handle))
{
using (handle) handle.Set();
}
}
catch
{
// If signalling fails, silently exit; the original keeps running.
}
}
/// <summary>Support a few command-line switches used by the installer and tests.</summary>
private static bool HandleCli(string[] args)
{
if (args.Length == 0) return false;
var command = args[0].ToLowerInvariant();
switch (command)
{
case "--status":
case "--register-autostart":
case "--no-autostart":
case "--simulate-copy":
case "--dump-settings":
case "--selftest":
case "--install-autostart-file":
case "--test-sound":
case "--probe-anchor":
case "--diagnose-anchor":
case "--dump-frames":
case "--snapshot-animations":
case "--snapshot":
case "--audio-list":
case "--audio-import":
case "--export-animation":
case "--export-gallery":
EnsureConsole();
break;
}
switch (command)
{
case "--autostart":
{
// Launched by Windows at sign-in: register (idempotent) and
// continue into the tray app rather than exiting here.
var ok = Autostart.Enable(out var error);
SettingsStore.Log(ok ? "autostart registered" : "autostart failed: " + error);
break; // fall through to the GUI below
}
case "--register-autostart":
{
var ok = Autostart.Enable(out var error);
Console.WriteLine(ok ? "autostart=enabled" : "autostart=failed: " + error);
Environment.ExitCode = ok ? 0 : 1;
return true;
}
case "--no-autostart":
Autostart.Disable();
Console.WriteLine("autostart=disabled");
return true;
case "--status":
{
var settings = SettingsStore.Load();
Console.WriteLine($"enabled={settings.Enabled}");
Console.WriteLine($"onlyWhenCopied={settings.OnlyWhenCopied}");
Console.WriteLine($"requireCtrlC={settings.RequireCtrlC}");
Console.WriteLine($"toast={settings.Toast.Enabled} position={settings.Toast.Position} text={settings.Toast.Text}");
Console.WriteLine($"sound={settings.Sound.Enabled} preset={settings.Sound.Preset} volume={settings.Sound.Volume}");
Console.WriteLine($"autostart={Autostart.IsEnabled()}");
Console.WriteLine($"exe={Environment.ProcessPath}");
Console.WriteLine($"data={SettingsStore.DataDir}");
return true;
}
case "--dump-settings":
Console.WriteLine(File.Exists(SettingsStore.SettingsFile)
? File.ReadAllText(SettingsStore.SettingsFile)
: "(no settings file; defaults in use)");
return true;
case "--selftest":
Diagnostics.Run();
return true;
case "--snapshot-animations":
{
EnsureConsole();
var outDir = args.Length > 1 ? args[1] : ".";
Snapshot.RunFilmstrip(outDir, args.Length > 2 ? args[2] : "已复制", 16);
return true;
}
case "--snapshot":
{
EnsureConsole();
var outPath = args.Length > 1 ? args[1] : "toast.png";
var text = args.Length > 2 ? args[2] : "已复制";
Snapshot.Run(outPath, text,
args.Length > 3 ? int.Parse(args[3]) : 14,
"#1F2430", "#F2F4F8", "#4D7CFE", "bottom-right");
return true;
}
case "--test-sound":
{
EnsureConsole();
var preset = args.Length > 1 ? args[1] : SettingsStore.Load().Sound.Preset;
Console.WriteLine("preset=" + preset);
Console.WriteLine("audioDir=" + SettingsStore.AudioDir);
if (preset.StartsWith("custom:", StringComparison.Ordinal))
{
var name = preset[7..];
var full = Path.Combine(SettingsStore.AudioDir, Path.GetFileName(name));
Console.WriteLine("file=" + full);
Console.WriteLine("exists=" + File.Exists(full));
if (File.Exists(full))
{
Console.WriteLine("bytes=" + new FileInfo(full).Length);
var head = File.ReadAllBytes(full).Take(16).ToArray();
Console.WriteLine("head=" + BitConverter.ToString(head));
}
}
SoundPlayerService.Preview(preset, args.Length > 2 ? double.Parse(args[2]) : 1.0);
// Playback runs on a background thread; give it real time so
// the process does not exit mid-note.
Thread.Sleep(4000);
Console.WriteLine("played (see log for errors)");
return true;
}
case "--probe-anchor":
{
EnsureConsole();
AnchorDiagnostics.Run();
return true;
}
case "--audio-delete":
{
EnsureConsole();
if (args.Length < 2)
{
Console.WriteLine("usage: --audio-delete <fileName> [...]");
return true;
}
var sb = new System.Text.StringBuilder();
foreach (var name in args.Skip(1))
{
var ok = AudioLibrary.Delete(Path.GetFileName(name));
sb.AppendLine((ok ? "DELETED: " : "FAILED: ") + name);
}
Console.WriteLine(sb.ToString());
try { File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "audio-delete.txt"), sb.ToString()); } catch { }
return true;
}
case "--audio-rename":
{
EnsureConsole();
if (args.Length < 3)
{
Console.WriteLine("usage: --audio-rename <fileName> <newDisplayName>");
return true;
}
var ok = AudioLibrary.Rename(Path.GetFileName(args[1]), args[2]);
var line = (ok ? "RENAMED: " : "FAILED: ") + args[1] + " -> " + args[2];
Console.WriteLine(line);
try { File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "audio-rename.txt"), line); } catch { }
return true;
}
case "--export-animation":
{
EnsureConsole();
var dir = args.Length > 1 ? args[1] : "frames";
var anim = args.Length > 2 ? args[2] : "pop";
var label = args.Length > 3 ? args[3] : "已复制";
var size = args.Length > 4 ? int.Parse(args[4]) : 22;
var count = args.Length > 5 ? int.Parse(args[5]) : 20;
var n = FrameExporter.Export(dir, anim, label, size, count, "fade", "#1F2430", "#4D7CFE");
Console.WriteLine($"exported {n} frames of '{anim}' to {dir}");
return true;
}
case "--export-gallery":
{
EnsureConsole();
var dir = args.Length > 1 ? args[1] : "gallery";
var label = args.Length > 2 ? args[2] : "已复制";
var size = args.Length > 3 ? int.Parse(args[3]) : 20;
var n = FrameExporter.ExportGallery(dir, label, size, "#1F2430", "#4D7CFE");
Console.WriteLine($"exported {n} gallery frames to {dir}");
return true;
}
case "--audio-list":
{
EnsureConsole();
var clips = AudioLibrary.List();
var sb = new System.Text.StringBuilder();
sb.AppendLine("count=" + clips.Count);
foreach (var c in clips)
{
sb.AppendLine($" display='{c.DisplayName}' file='{c.FileName}' bytes={c.Bytes}");
}
Console.WriteLine(sb.ToString());
try { File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "audio-list.txt"), sb.ToString()); } catch { }
return true;
}
case "--audio-import":
{
EnsureConsole();
if (args.Length < 2)
{
Console.WriteLine("usage: --audio-import <file> [...]");
return true;
}
var sb = new System.Text.StringBuilder();
foreach (var path in args.Skip(1))
{
var r = AudioLibrary.Import(path);
sb.AppendLine(r.Ok
? $"{(r.WasDuplicate ? "DUPLICATE" : "ADDED")}: display='{r.Clip!.DisplayName}' file='{r.Clip.FileName}'"
: "FAILED: " + r.Error);
}
Console.WriteLine(sb.ToString());
try { File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "audio-import.txt"), sb.ToString()); } catch { }
return true;
}
case "--dump-frames":
{
EnsureConsole();
var report = new System.Text.StringBuilder();
foreach (var name in SettingsStore.Animations)
{
report.AppendLine("=== " + name + " ===");
foreach (var t in new[] { 0.0, 0.25, 0.5, 0.75, 1.0 })
{
var f = ToastAnimations.Entrance(name, t, new Size(120, 96), 1f);
report.AppendLine($" t={t:F2} offset=({f.Offset.X:F1},{f.Offset.Y:F1}) " +
$"scale={f.Scale:F3} alpha={f.Alpha:F3} rot={f.Rotation:F1}");
}
}
Console.WriteLine(report.ToString());
try
{
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "frames.txt"),
report.ToString());
}
catch { }
return true;
}
case "--show-probe-toast":
{
EnsureConsole();
var sel = SelectionLocator.TryGetSelectionBounds();
var lines = new System.Text.StringBuilder();
void L(string s) { lines.AppendLine(s); Console.WriteLine(s); }
L("position=" + SettingsStore.Load().Toast.Position);
L("selection=" + (sel is { } rr
? $"{rr.X},{rr.Y} {rr.Width}x{rr.Height}"
: "none (will fall back to above the pointer)"));
var cursor = System.Windows.Forms.Cursor.Position;
L($"cursor={cursor.X},{cursor.Y}");
var probeStyle = SettingsStore.Load().Toast;
using var probe = new ToastForm(probeStyle.Text, probeStyle, sel);
L($"toastWindow={probe.Location.X},{probe.Location.Y} size={probe.Width}x{probe.Height}");
try
{
File.WriteAllText(System.IO.Path.Combine(AppContext.BaseDirectory, "probe-report.txt"),
lines.ToString());
}
catch { }
return true;
}
case "--verify-pipeline":
// Exercises the real detection -> toast -> sound path without
// needing OS-level input injection (unavailable in sandboxes).
EnsureConsole();
VerifyPipeline();
return true;
case "--install-autostart-file":
// Writes a .cmd launcher plus a folder with instructions; the
// user drops the shortcut into shell:startup. Used where the
// process cannot touch the Run key.
EnsureConsole();
Console.WriteLine(Autostart.WriteStartupHelper());
return true;
case "--simulate-copy":
// Verification hook: run the real feedback pipeline once, as if
// a copy happened, so the toast and sound can be checked without
// driving the physical keyboard.
ApplicationConfiguration.Initialize();
RunSimulatedCopy(args.Length > 1 ? args[1] : "simulated");
return true;
case "--test-toast":
{
ApplicationConfiguration.Initialize();
var style = SettingsStore.Load().Toast;
if (args.Length > 1) style.Text = args[1];
var toast = new ToastForm(style.Text, style);
toast.ShowNoActivate();
Application.Run(new ApplicationContext(toast));
return true;
}
case "--quit":
SignalExistingInstance();
return true;
}
return false;
}
/// <summary>
/// Drive the real detector with a simulated chord plus a real clipboard
/// change, and report whether a toast window actually appeared. This is
/// the verification path for environments where input cannot be injected.
/// </summary>
private static void VerifyPipeline()
{
ApplicationConfiguration.Initialize();
var settings = SettingsStore.Load();
settings.Toast.DurationMs = 2500;
settings.Sound.Enabled = false;
using var window = new MessageWindow();
using var detector = new CopyDetector(window);
var fired = 0;
detector.Copied += (len, src, selection) =>
{
fired++;
Console.WriteLine($"detected: length={len} source={src} " +
$"selection={(selection is { } r ? $"{r.X},{r.Y} {r.Width}x{r.Height}" : "none")}");
};
detector.Start();
Console.WriteLine("hook=" + detector.HookOk);
// Real clipboard content, so the detector reads genuine text.
var content = "DSHCF-verify-" + DateTime.Now.Ticks;
try
{
Clipboard.SetText(content);
Console.WriteLine("clipboard-set=winforms");
}
catch (Exception ex)
{
Console.WriteLine("clipboard-set-winforms-failed: " + ex.Message);
}
var readBack = "";
try
{
readBack = Clipboard.ContainsText() ? Clipboard.GetText() : "";
}
catch (Exception ex)
{
Console.WriteLine("clipboard-read-failed: " + ex.Message);
}
Console.WriteLine("clipboard-len=" + readBack.Length);
// First: a clipboard change WITHOUT the chord must not fire.
detector.SimulateClipboardUpdate(force: true);
Console.WriteLine("silent-without-chord=" + (fired == 0));
// Then: the chord, followed by the clipboard change, must fire.
detector.SimulateCopyChord();
var shown = 0;
var context = new ApplicationContext();
var toast = new ToastForm(settings.Toast.Text, settings.Toast); toast.Shown += (_, _) => { shown++; };
toast.FormClosed += (_, _) => Application.Exit();
var timer = new System.Windows.Forms.Timer { Interval = 150 };
timer.Tick += (_, _) =>
{
timer.Stop();
detector.SimulateClipboardUpdate(force: true);
Console.WriteLine("fired-after-chord=" + (fired == 1));
Console.WriteLine("toast-about-to-show");
toast.ShowNoActivate();
toast.Show();
Console.WriteLine("toast-shown-call-returned visible=" + toast.Visible);
};
timer.Start();
var kill = new System.Windows.Forms.Timer { Interval = 4000 };
kill.Tick += (_, _) => { kill.Stop(); Application.Exit(); };
kill.Start();
Application.Run(context);
Console.WriteLine("toast-shown-event=" + shown);
Console.WriteLine("pipeline=" + (fired == 1 ? "detect-OK" : "detect-FAILED") + "," +
(shown >= 1 ? "toast-OK" : "toast-FAILED"));
}
/// <summary>Render one toast and play one sound, then exit.</summary>
private static void RunSimulatedCopy(string text)
{
var settings = SettingsStore.Load();
if (!settings.Toast.Enabled && !settings.Sound.Enabled) return;
var toast = new ToastForm(text, settings.Toast);
SoundPlayerService.Play(settings.Sound);
var context = new ApplicationContext();
toast.FormClosed += (_, _) => Application.Exit();
context.MainForm = toast;
toast.ShowNoActivate();
// Guard against a toast that never closes.
var killSwitch = new System.Windows.Forms.Timer { Interval = 6000 };
killSwitch.Tick += (_, _) => { killSwitch.Stop(); Application.Exit(); };
killSwitch.Start();
Application.Run(context);
}
}
internal static class App
{
/// <summary>The running tray application, for components that need settings.</summary>
public static TrayApplication? Current { get; set; }
}
/// <summary>
/// Registers the app to start with Windows via the per-user Run key, which
/// needs no elevation and keeps the setting in HKCU.
/// </summary>
internal static class Autostart
{
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string ValueName = "AfterCtrlC";
/// <summary>Registry value written by versions before the rename.</summary>
private const string LegacyValueName = "DSHCopyFeedback";
private static string ExecutablePath =>
Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule?.FileName ?? "";
public static bool IsEnabled()
{
// Accept either the current value or the one written before the rename,
// so upgrading does not silently look like autostart was switched off.
foreach (var name in new[] { ValueName, LegacyValueName })
{
var value = ReadValue(name);
if (!string.IsNullOrEmpty(value) && PathExists(value)) return true;
}
return false;
}
private static string? ReadValue(string name)
{
try
{
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RunKey);
if (key?.GetValue(name) is string direct) return direct;
}
catch
{
// Fall through to reading it through PowerShell.
}
var stdout = RunPowerShell("$v = (Get-ItemProperty -Path 'HKCU:\\" + RunKey +
"' -Name '" + name + "' -ErrorAction SilentlyContinue).'" +
name + "'; if ($v) { $v }").Trim();
return stdout.Length == 0 ? null : stdout;
}
/// <summary>Whether the executable a Run value points at still exists.</summary>
private static bool PathExists(string value)
{
// A stale entry (the exe was moved) counts as disabled.
var path = value.Trim();
if (path.StartsWith('"'))
{
var end = path.IndexOf('"', 1);
if (end > 1) path = path[1..end];
}
else
{
var exeAt = path.IndexOf(".exe", StringComparison.OrdinalIgnoreCase);
if (exeAt > 0) path = path[..(exeAt + 4)];
}
return File.Exists(path);
}
public static bool Enable(out string error)
{
error = "";
var exe = ExecutablePath;
if (string.IsNullOrEmpty(exe))
{
error = "无法确定程序路径";
return false;
}
if (!File.Exists(exe))
{
error = "程序文件不存在:" + exe;
return false;
}
// Prefer the in-process write; fall back to PowerShell, which succeeds
// even where a sandboxed process is denied HKCU write access.
try
{
using var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(RunKey, writable: true);
if (key != null)
{
key.SetValue(ValueName, "\"" + exe + "\" --autostart",
Microsoft.Win32.RegistryValueKind.String);
return true;
}
}
catch (Exception ex)
{
error = ex.GetType().Name + ": " + ex.Message;
}
var script = string.Join("\r\n", new[]
{
"$p = 'HKCU:\\" + RunKey + "'",
"if (-not (Test-Path $p)) { New-Item -Path $p -Force | Out-Null }",
"Set-ItemProperty -Path $p -Name '" + ValueName + "' -Value " + PsQuote("\"" + exe + "\" --autostart"),
"if ((Get-ItemProperty -Path $p -Name '" + ValueName + "' -ErrorAction SilentlyContinue)) { 'ok' } else { 'fail' }",
});
var result = RunPowerShell(script).Trim();
if (result == "ok")
{
error = "";
return true;
}
if (string.IsNullOrEmpty(error)) error = "写入注册表被拒绝:" + result;
SettingsStore.Log("autostart enable: " + error);
return false;
}
public static bool Enable() => Enable(out _);
private static string PsQuote(string value) => "'" + value.Replace("'", "''") + "'";
/// <summary>Run a PowerShell snippet and return its stdout.</summary>
private static string RunPowerShell(string script)
{
try
{
var psi = new ProcessStartInfo
{
FileName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.System),
@"WindowsPowerShell\v1.0\powershell.exe"),
Arguments = "-NoProfile -NonInteractive -EncodedCommand " +
Convert.ToBase64String(Encoding.Unicode.GetBytes(script)),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8,
};
using var process = Process.Start(psi);
if (process == null) return "";
var stdout = process.StandardOutput.ReadToEnd();
process.WaitForExit(10000);
return stdout;
}
catch (Exception ex)
{
SettingsStore.Log("powershell: " + ex.Message);
return "";
}
}
public static void Disable()
{
// Clear both the current value and the one written before the rename,
// so "disable" really means disabled regardless of which version wrote it.
foreach (var name in new[] { ValueName, LegacyValueName })
{
try
{
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RunKey, writable: true);
key?.DeleteValue(name, throwOnMissingValue: false);
}
catch (Exception ex)
{
SettingsStore.Log("autostart disable (direct): " + ex.Message);
}
// Verify; if the in-process delete did not take, delegate to PowerShell.
if (ReadRaw(name).Length > 0)
{
RunPowerShell("Remove-ItemProperty -Path 'HKCU:\\" + RunKey + "' -Name '" +
name + "' -ErrorAction SilentlyContinue; 'ok'");
}
}
}
private static string ReadRaw(string name)
{
try
{
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RunKey);
return key?.GetValue(name) as string ?? "";
}
catch
{
return "";
}
}
/// <summary>
/// Fallback for environments where the Run key is unreachable: write a
/// launcher beside the exe and tell the user to drop it in shell:startup.
/// Returns a short report for the console.
/// </summary>
public static string WriteStartupHelper()
{
var exe = ExecutablePath;
if (string.IsNullOrEmpty(exe)) return "无法确定程序路径";
var helper = Path.Combine(Path.GetDirectoryName(exe)!, "启动 DSH 复制反馈.cmd");
var body = "@echo off\r\n" +
"rem 把本文件复制到 shell:startup 文件夹即可开机自启\r\n" +
"start \"\" \"" + exe + "\" --autostart\r\n";
try
{
File.WriteAllText(helper, body, new UTF8Encoding(false));
}
catch (Exception ex)
{
return "写入失败:" + ex.Message;
}
try
{
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = "\"" + Path.GetDirectoryName(exe) + "\"",
UseShellExecute = true,
});
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = "shell:startup",
UseShellExecute = true,
});
}
catch
{
// Explorer is a convenience, not a requirement.
}
return "已生成:" + helper + Environment.NewLine +
"已打开程序文件夹和「启动」文件夹,把该 .cmd 拖进「启动」即可。";
}
}