forked from SuperGouge/ChanThreadWatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
71 lines (66 loc) · 2.57 KB
/
Program.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
using System;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace JDP {
internal static class Program {
private static Mutex _mutex;
[STAThread]
private static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (!ObtainMutex()) {
MessageBox.Show("Another instance of this program is running.", "Already Running", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Application.Run(new frmChanThreadWatch());
}
public static bool ObtainMutex() {
return ObtainMutex(Settings.GetSettingsDirectory());
}
public static bool ObtainMutex(string settingsFolder) {
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
MutexSecurity security = new MutexSecurity();
bool useDefaultSecurity = false;
bool createdNew;
try {
security.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
security.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
security.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));
}
catch (Exception ex) {
if (ex is ArgumentOutOfRangeException || ex is NotImplementedException) {
// Workaround for Mono
useDefaultSecurity = true;
}
else {
throw;
}
}
string name = @"Global\ChanThreadWatch_" + General.Calculate64BitMD5(Encoding.UTF8.GetBytes(
settingsFolder.ToUpperInvariant())).ToString("X16");
Mutex mutex = !useDefaultSecurity ?
new Mutex(false, name, out createdNew, security) :
new Mutex(false, name);
try {
if (!mutex.WaitOne(0, false)) {
return false;
}
}
catch (AbandonedMutexException) { }
ReleaseMutex();
_mutex = mutex;
return true;
}
public static void ReleaseMutex() {
if (_mutex == null) return;
try {
_mutex.ReleaseMutex();
}
catch { }
_mutex = null;
}
}
}