-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
109 lines (96 loc) · 3.34 KB
/
Copy pathProgram.cs
File metadata and controls
109 lines (96 loc) · 3.34 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
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using TaaProxy.Views;
namespace TaaProxy
{
internal static class Program
{
private static Mutex? _mutex;
[STAThread]
public static void Main()
{
if (ApplyPendingSelfUpdate()) return;
_mutex = new Mutex(true, "TaaClient_Singleton_Mutex_CSharp", out bool isNew);
if (!isNew) { BringToFront(); return; }
SystemProxy.ClearStale();
TempConfigCleaner.DeleteOrphaned();
AppDomain.CurrentDomain.ProcessExit += (_, _) => { SystemProxy.Set(false); KillSwitch.Set(false); };
var app = new TaaApp();
app.Run(new MainWindow());
}
private static bool ApplyPendingSelfUpdate()
{
try
{
var exe = Process.GetCurrentProcess().MainModule?.FileName;
if (exe == null) return false;
var pending = exe + ".new";
if (!File.Exists(pending)) return false;
File.Replace(pending, exe, destinationBackupFileName: null);
try
{
foreach (var hWnd in GetVisibleWindows())
NativeInterop.ShowWindow(hWnd, 0);
}
catch { }
Process.Start(new ProcessStartInfo(exe) { UseShellExecute = true });
return true;
}
catch
{
try
{
var exe = Process.GetCurrentProcess().MainModule?.FileName;
if (exe != null) File.Delete(exe + ".new");
}
catch { }
return false;
}
}
private static List<IntPtr> GetVisibleWindows()
{
var result = new List<IntPtr>();
var pid = (uint)Process.GetCurrentProcess().Id;
NativeInterop.EnumWindows((hWnd, _) =>
{
NativeInterop.GetWindowThreadProcessId(hWnd, out uint ownerPid);
if (ownerPid == pid && NativeInterop.IsWindowVisible(hWnd))
result.Add(hWnd);
return true;
}, IntPtr.Zero);
return result;
}
public static void ReleaseMutex()
{
try { _mutex?.ReleaseMutex(); } catch { }
_mutex?.Dispose();
_mutex = null;
}
private static void BringToFront()
{
const int WM_SHOW_INSTANCE = 0x0401;
var ourExe = Process.GetCurrentProcess().MainModule?.FileName ?? "";
NativeInterop.EnumWindows((hWnd, _) =>
{
NativeInterop.GetWindowThreadProcessId(hWnd, out uint pid);
try
{
var proc = Process.GetProcessById((int)pid);
if (string.Equals(proc.MainModule?.FileName, ourExe, StringComparison.OrdinalIgnoreCase))
{
NativeInterop.PostMessage(hWnd, WM_SHOW_INSTANCE, IntPtr.Zero, IntPtr.Zero);
return false;
}
}
catch { }
return true;
}, IntPtr.Zero);
}
}
}