-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathWpfSingleInstance.cs
76 lines (62 loc) · 2.42 KB
/
WpfSingleInstance.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
using System;
using System.Threading;
using System.Windows;
namespace WpfSingleInstanceByEventWaitHandle
{
public static class WpfSingleInstance
{
private static bool AlreadyProcessedOnThisInstance;
internal static void Make(string appName, bool uniquePerUser = true)
{
if(AlreadyProcessedOnThisInstance)
{
return;
}
AlreadyProcessedOnThisInstance = true;
Application app = Application.Current;
string eventName = uniquePerUser
? $"{appName}-{Environment.MachineName}-{Environment.UserDomainName}-{Environment.UserName}"
: $"{appName}-{Environment.MachineName}";
bool isSecondaryInstance = true;
EventWaitHandle eventWaitHandle = null;
try
{
eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
}
catch
{
// This code only runs on the first instance.
isSecondaryInstance = false;
}
if (isSecondaryInstance)
{
ActivateFirstInstanceWindow(eventWaitHandle);
// Let's produce a non-interceptable exit (2009 year approach).
Environment.Exit(0);
}
RegisterFirstInstanceWindowActivation(app, eventName);
}
private static void ActivateFirstInstanceWindow(EventWaitHandle eventWaitHandle)
{
// Let's notify the first instance to activate its main window.
_ = eventWaitHandle.Set();
}
private static void RegisterFirstInstanceWindowActivation(Application app, string eventName)
{
EventWaitHandle eventWaitHandle = new EventWaitHandle(
false,
EventResetMode.AutoReset,
eventName);
_ = ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, app, Timeout.Infinite, false);
eventWaitHandle.Close();
}
private static void WaitOrTimerCallback(object state, bool timedOut)
{
Application app = (Application)state;
_ = app.Dispatcher.BeginInvoke(new Action(() =>
{
_ = Application.Current.MainWindow.Activate();
}));
}
}
}