-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
58 lines (51 loc) · 1.59 KB
/
Program.cs
File metadata and controls
58 lines (51 loc) · 1.59 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
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace MWBToggle;
internal static class Program
{
private const string MutexName = "Global\\MWBToggle_SingleInstance";
[STAThread]
static void Main()
{
// Mirror AHK's #SingleInstance Force — kill any previous instance
// so the new one (with potentially updated config) takes over.
KillPreviousInstance();
using var mutex = new Mutex(true, MutexName, out bool createdNew);
if (!createdNew)
{
// Race condition: another instance started between kill and mutex.
// Wait briefly for it to exit, then retry.
Thread.Sleep(500);
mutex.Dispose();
using var retryMutex = new Mutex(true, MutexName, out bool retryCreated);
if (!retryCreated)
return; // Still couldn't acquire — give up
}
ApplicationConfiguration.Initialize();
Application.Run(new MWBToggleApp());
}
private static void KillPreviousInstance()
{
int myPid = Environment.ProcessId;
using var self = Process.GetCurrentProcess();
string myName = self.ProcessName;
foreach (var proc in Process.GetProcessesByName(myName))
{
try
{
if (proc.Id != myPid)
proc.Kill();
}
catch
{
// Process may have already exited — ignore
}
finally
{
proc.Dispose();
}
}
}
}