-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathSingleAppInstance.cs
96 lines (85 loc) · 3.37 KB
/
SingleAppInstance.cs
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
// <copyright file="SingleAppInstance.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SystemTrayMenu.Utilities
{
using System;
using System.Diagnostics;
using System.Linq;
using SystemTrayMenu.Business;
internal static class SingleAppInstance
{
private const string IpcServiceName = nameof(SingleAppInstance);
private const string IpcWakeupCmd = "wakeup";
private const string IpcWakeupResponseOK = "OK";
private static IpcPipe? ipcPipe;
internal static event Action? Wakeup;
internal static bool Initialize()
{
bool success = true;
try
{
foreach (Process p in
Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).
Where(s => s.Id != Environment.ProcessId))
{
try
{
if (Properties.Settings.Default.SendHotkeyInsteadKillOtherInstances)
{
// Instead of using hotkeys we use IPC via pipes
string pipeName = IpcServiceName + "-" + p.Id.ToString();
ipcPipe = new(1, pipeName);
string response = ipcPipe.SendToServer(IpcWakeupCmd) ?? string.Empty;
if (!string.Equals(response, IpcWakeupResponseOK))
{
throw new Exception("Error at IPC pipe \"" + pipeName + "\": \"" + response + "\"");
}
ipcPipe.Dispose();
ipcPipe = null;
success = false; // This is "success" but it means we cannot start this instance -> false
}
else
{
if (!p.CloseMainWindow())
{
p.Kill();
}
p.WaitForExit();
p.Close();
}
}
catch (Exception ex)
{
Log.Error("Run as single instance failed", ex);
success = false;
}
}
}
catch (Exception ex)
{
Log.Error("Run as single instance failed", ex);
success = false;
}
if (success)
{
// We are the only process running, so we are responsible for the IPC server
ipcPipe = new(1, IpcServiceName + "-" + Environment.ProcessId.ToString());
ipcPipe.StartServer((request) =>
{
if (string.Equals(request, IpcWakeupCmd))
{
Wakeup?.Invoke();
return IpcWakeupResponseOK;
}
return string.Empty;
});
}
return success;
}
internal static void Unload()
{
ipcPipe?.Dispose();
}
}
}