-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingleInstance.cs
494 lines (421 loc) · 17.1 KB
/
SingleInstance.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//-----------------------------------------------------------------------
// <copyright file="SingleInstance.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// This class checks to make sure that only one instance of
// this application is running at a time.
// </summary>
//-----------------------------------------------------------------------
namespace Microsoft.Shell
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using System.Xml.Serialization;
using System.Security;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;
internal enum WM
{
NULL = 0x0000,
CREATE = 0x0001,
DESTROY = 0x0002,
MOVE = 0x0003,
SIZE = 0x0005,
ACTIVATE = 0x0006,
SETFOCUS = 0x0007,
KILLFOCUS = 0x0008,
ENABLE = 0x000A,
SETREDRAW = 0x000B,
SETTEXT = 0x000C,
GETTEXT = 0x000D,
GETTEXTLENGTH = 0x000E,
PAINT = 0x000F,
CLOSE = 0x0010,
QUERYENDSESSION = 0x0011,
QUIT = 0x0012,
QUERYOPEN = 0x0013,
ERASEBKGND = 0x0014,
SYSCOLORCHANGE = 0x0015,
SHOWWINDOW = 0x0018,
ACTIVATEAPP = 0x001C,
SETCURSOR = 0x0020,
MOUSEACTIVATE = 0x0021,
CHILDACTIVATE = 0x0022,
QUEUESYNC = 0x0023,
GETMINMAXINFO = 0x0024,
WINDOWPOSCHANGING = 0x0046,
WINDOWPOSCHANGED = 0x0047,
CONTEXTMENU = 0x007B,
STYLECHANGING = 0x007C,
STYLECHANGED = 0x007D,
DISPLAYCHANGE = 0x007E,
GETICON = 0x007F,
SETICON = 0x0080,
NCCREATE = 0x0081,
NCDESTROY = 0x0082,
NCCALCSIZE = 0x0083,
NCHITTEST = 0x0084,
NCPAINT = 0x0085,
NCACTIVATE = 0x0086,
GETDLGCODE = 0x0087,
SYNCPAINT = 0x0088,
NCMOUSEMOVE = 0x00A0,
NCLBUTTONDOWN = 0x00A1,
NCLBUTTONUP = 0x00A2,
NCLBUTTONDBLCLK = 0x00A3,
NCRBUTTONDOWN = 0x00A4,
NCRBUTTONUP = 0x00A5,
NCRBUTTONDBLCLK = 0x00A6,
NCMBUTTONDOWN = 0x00A7,
NCMBUTTONUP = 0x00A8,
NCMBUTTONDBLCLK = 0x00A9,
SYSKEYDOWN = 0x0104,
SYSKEYUP = 0x0105,
SYSCHAR = 0x0106,
SYSDEADCHAR = 0x0107,
COMMAND = 0x0111,
SYSCOMMAND = 0x0112,
MOUSEMOVE = 0x0200,
LBUTTONDOWN = 0x0201,
LBUTTONUP = 0x0202,
LBUTTONDBLCLK = 0x0203,
RBUTTONDOWN = 0x0204,
RBUTTONUP = 0x0205,
RBUTTONDBLCLK = 0x0206,
MBUTTONDOWN = 0x0207,
MBUTTONUP = 0x0208,
MBUTTONDBLCLK = 0x0209,
MOUSEWHEEL = 0x020A,
XBUTTONDOWN = 0x020B,
XBUTTONUP = 0x020C,
XBUTTONDBLCLK = 0x020D,
MOUSEHWHEEL = 0x020E,
CAPTURECHANGED = 0x0215,
ENTERSIZEMOVE = 0x0231,
EXITSIZEMOVE = 0x0232,
IME_SETCONTEXT = 0x0281,
IME_NOTIFY = 0x0282,
IME_CONTROL = 0x0283,
IME_COMPOSITIONFULL = 0x0284,
IME_SELECT = 0x0285,
IME_CHAR = 0x0286,
IME_REQUEST = 0x0288,
IME_KEYDOWN = 0x0290,
IME_KEYUP = 0x0291,
NCMOUSELEAVE = 0x02A2,
DWMCOMPOSITIONCHANGED = 0x031E,
DWMNCRENDERINGCHANGED = 0x031F,
DWMCOLORIZATIONCOLORCHANGED = 0x0320,
DWMWINDOWMAXIMIZEDCHANGE = 0x0321,
#region Windows 7
DWMSENDICONICTHUMBNAIL = 0x0323,
DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326,
#endregion
USER = 0x0400,
// This is the hard-coded message value used by WinForms for Shell_NotifyIcon.
// It's relatively safe to reuse.
TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024
APP = 0x8000,
}
[SuppressUnmanagedCodeSecurity]
internal static class NativeMethods
{
/// <summary>
/// Delegate declaration that matches WndProc signatures.
/// </summary>
public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled);
[DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)]
private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs);
[DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)]
private static extern IntPtr _LocalFree(IntPtr hMem);
public static string[] CommandLineToArgvW(string cmdLine)
{
IntPtr argv = IntPtr.Zero;
try
{
int numArgs = 0;
argv = _CommandLineToArgvW(cmdLine, out numArgs);
if (argv == IntPtr.Zero)
{
throw new Win32Exception();
}
var result = new string[numArgs];
for (int i = 0; i < numArgs; i++)
{
IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr)));
result[i] = Marshal.PtrToStringUni(currArg);
}
return result;
}
finally
{
IntPtr p = _LocalFree(argv);
// Otherwise LocalFree failed.
// Assert.AreEqual(IntPtr.Zero, p);
}
}
}
public interface ISingleInstanceApp
{
bool SignalExternalCommandLineArgs(IList<string> args);
}
/// <summary>
/// This class checks to make sure that only one instance of
/// this application is running at a time.
/// </summary>
/// <remarks>
/// Note: this class should be used with some caution, because it does no
/// security checking. For example, if one instance of an app that uses this class
/// is running as Administrator, any other instance, even if it is not
/// running as Administrator, can activate it with command line arguments.
/// For most apps, this will not be much of an issue.
/// </remarks>
public static class SingleInstance<TApplication>
where TApplication : Application, ISingleInstanceApp
{
#region Private Fields
/// <summary>
/// String delimiter used in channel names.
/// </summary>
private const string Delimiter = ":";
/// <summary>
/// Suffix to the channel name.
/// </summary>
private const string ChannelNameSuffix = "SingeInstanceIPCChannel";
/// <summary>
/// Remote service name.
/// </summary>
private const string RemoteServiceName = "SingleInstanceApplicationService";
/// <summary>
/// IPC protocol used (string).
/// </summary>
private const string IpcProtocol = "ipc://";
/// <summary>
/// Application mutex.
/// </summary>
private static Mutex singleInstanceMutex;
/// <summary>
/// IPC channel for communications.
/// </summary>
private static IpcServerChannel channel;
/// <summary>
/// List of command line arguments for the application.
/// </summary>
private static IList<string> commandLineArgs;
#endregion
#region Public Properties
/// <summary>
/// Gets list of command line arguments for the application.
/// </summary>
public static IList<string> CommandLineArgs
{
get { return commandLineArgs; }
}
#endregion
#region Public Methods
/// <summary>
/// Checks if the instance of the application attempting to start is the first instance.
/// If not, activates the first instance.
/// </summary>
/// <returns>True if this is the first instance of the application.</returns>
public static bool InitializeAsFirstInstance(string uniqueName)
{
commandLineArgs = GetCommandLineArgs(uniqueName);
// Build unique application Id and the IPC channel name.
string applicationIdentifier = uniqueName + Environment.UserName;
string channelName = String.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix);
// Create mutex based on unique application Id to check if this is the first instance of the application.
bool firstInstance;
singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance);
if (firstInstance)
{
CreateRemoteService(channelName);
}
else
{
SignalFirstInstance(channelName, commandLineArgs);
}
return firstInstance;
}
/// <summary>
/// Cleans up single-instance code, clearing shared resources, mutexes, etc.
/// </summary>
public static void Cleanup()
{
if (singleInstanceMutex != null)
{
singleInstanceMutex.Close();
singleInstanceMutex = null;
}
if (channel != null)
{
ChannelServices.UnregisterChannel(channel);
channel = null;
}
}
#endregion
#region Private Methods
/// <summary>
/// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved.
/// </summary>
/// <returns>List of command line arg strings.</returns>
private static IList<string> GetCommandLineArgs(string uniqueApplicationName)
{
string[] args = null;
if (AppDomain.CurrentDomain.ActivationContext == null)
{
// The application was not clickonce deployed, get args from standard API's
args = Environment.GetCommandLineArgs();
}
else
{
// The application was clickonce deployed
// Clickonce deployed apps cannot recieve traditional commandline arguments
// As a workaround commandline arguments can be written to a shared location before
// the app is launched and the app can obtain its commandline arguments from the
// shared location
string appFolderPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName);
string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt");
if (File.Exists(cmdLinePath))
{
try
{
using (TextReader reader = new StreamReader(cmdLinePath, System.Text.Encoding.Unicode))
{
args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
}
File.Delete(cmdLinePath);
}
catch (IOException)
{
}
}
}
if (args == null)
{
args = new string[] { };
}
return new List<string>(args);
}
/// <summary>
/// Creates a remote service for communication.
/// </summary>
/// <param name="channelName">Application's IPC channel name.</param>
private static void CreateRemoteService(string channelName)
{
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props = new Dictionary<string, string>();
props["name"] = channelName;
props["portName"] = channelName;
props["exclusiveAddressUse"] = "false";
// Create the IPC Server channel with the channel properties
channel = new IpcServerChannel(props, serverProvider);
// Register the channel with the channel services
ChannelServices.RegisterChannel(channel, true);
// Expose the remote service with the REMOTE_SERVICE_NAME
IPCRemoteService remoteService = new IPCRemoteService();
RemotingServices.Marshal(remoteService, RemoteServiceName);
}
/// <summary>
/// Creates a client channel and obtains a reference to the remoting service exposed by the server -
/// in this case, the remoting service exposed by the first instance. Calls a function of the remoting service
/// class to pass on command line arguments from the second instance to the first and cause it to activate itself.
/// </summary>
/// <param name="channelName">Application's IPC channel name.</param>
/// <param name="args">
/// Command line arguments for the second instance, passed to the first instance to take appropriate action.
/// </param>
private static void SignalFirstInstance(string channelName, IList<string> args)
{
IpcClientChannel secondInstanceChannel = new IpcClientChannel();
ChannelServices.RegisterChannel(secondInstanceChannel, true);
string remotingServiceUrl = IpcProtocol + channelName + "/" + RemoteServiceName;
// Obtain a reference to the remoting service exposed by the server i.e the first instance of the application
IPCRemoteService firstInstanceRemoteServiceReference = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), remotingServiceUrl);
// Check that the remote service exists, in some cases the first instance may not yet have created one, in which case
// the second instance should just exit
if (firstInstanceRemoteServiceReference != null)
{
// Invoke a method of the remote service exposed by the first instance passing on the command line
// arguments and causing the first instance to activate itself
Trace.WriteLine("firstInstanceRemoteServiceReference = " + firstInstanceRemoteServiceReference);
firstInstanceRemoteServiceReference.InvokeFirstInstance(args);
}
}
/// <summary>
/// Callback for activating first instance of the application.
/// </summary>
/// <param name="arg">Callback argument.</param>
/// <returns>Always null.</returns>
private static object ActivateFirstInstanceCallback(object arg)
{
// Get command line args to be passed to first instance
IList<string> args = arg as IList<string>;
ActivateFirstInstance(args);
return null;
}
/// <summary>
/// Activates the first instance of the application with arguments from a second instance.
/// </summary>
/// <param name="args">List of arguments to supply the first instance of the application.</param>
private static void ActivateFirstInstance(IList<string> args)
{
// Set main window state and process command line args
if (Application.Current == null)
{
return;
}
((TApplication)Application.Current).SignalExternalCommandLineArgs(args);
}
#endregion
#region Private Classes
/// <summary>
/// Remoting service class which is exposed by the server i.e the first instance and called by the second instance
/// to pass on the command line arguments to the first instance and cause it to activate itself.
/// </summary>
private class IPCRemoteService : MarshalByRefObject
{
/// <summary>
/// Activates the first instance of the application.
/// </summary>
/// <param name="args">List of arguments to pass to the first instance.</param>
public void InvokeFirstInstance(IList<string> args)
{
if (Application.Current != null)
{
// Do an asynchronous call to ActivateFirstInstance function
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Normal, new DispatcherOperationCallback(SingleInstance<TApplication>.ActivateFirstInstanceCallback), args);
}
}
/// <summary>
/// Remoting Object's ease expires after every 5 minutes by default. We need to override the InitializeLifetimeService class
/// to ensure that lease never expires.
/// </summary>
/// <returns>Always null.</returns>
public override object InitializeLifetimeService()
{
return null;
}
}
#endregion
}
}