mirror of
https://github.com/terrymacdonald/DisplayMagician.git
synced 2024-08-30 18:32:20 +00:00
[WIP] Initial part of singleInstance
This commit is contained in:
parent
2deee7eb15
commit
bdd93e0956
@ -122,7 +122,6 @@
|
||||
<Compile Include="IconFromFile.cs" />
|
||||
<Compile Include="IconUtils.cs" />
|
||||
<Compile Include="ImageUtils.cs" />
|
||||
<Compile Include="ISingleInstanceApp.cs" />
|
||||
<Compile Include="NativeMethods.cs" />
|
||||
<Compile Include="Processes\ImpersonationHelper.cs" />
|
||||
<Compile Include="MessageItem.cs" />
|
||||
@ -215,10 +214,6 @@
|
||||
</Compile>
|
||||
<Compile Include="Utils.cs" />
|
||||
<Compile Include="Validators.cs" />
|
||||
<Compile Include="InterProcess\IPCClient.cs" />
|
||||
<Compile Include="InterProcess\InstanceStatus.cs" />
|
||||
<Compile Include="InterProcess\IService.cs" />
|
||||
<Compile Include="InterProcess\IPCService.cs" />
|
||||
<Compile Include="Resources\Language.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DesignTime>True</DesignTime>
|
||||
|
@ -1,18 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DisplayMagician
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
|
||||
/// <summary>
|
||||
/// http://blogs.microsoft.co.il/arik/2010/05/28/wpf-single-instance-application/
|
||||
/// </summary>
|
||||
public interface ISingleInstanceApp
|
||||
{
|
||||
bool SignalExternalCommandLineArgs(IList<string> args);
|
||||
}
|
||||
}
|
@ -1,100 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.ServiceModel;
|
||||
using System.ServiceModel.Description;
|
||||
|
||||
namespace DisplayMagician.InterProcess
|
||||
{
|
||||
internal class IPCClient : ClientBase<IService>, IService
|
||||
{
|
||||
|
||||
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
public IPCClient(Process process)
|
||||
: base(
|
||||
new ServiceEndpoint(
|
||||
ContractDescription.GetContract(typeof(IService)),
|
||||
new NetNamedPipeBinding(),
|
||||
new EndpointAddress(
|
||||
$"net.pipe://localhost/DisplayMagician_IPC{process.Id}/Service")))
|
||||
{
|
||||
}
|
||||
|
||||
public int HoldProcessId
|
||||
{
|
||||
get => Channel.HoldProcessId;
|
||||
}
|
||||
|
||||
public InstanceStatus Status
|
||||
{
|
||||
get => Channel.Status;
|
||||
}
|
||||
|
||||
public void StopHold()
|
||||
{
|
||||
Channel.StopHold();
|
||||
}
|
||||
|
||||
public static IEnumerable<IPCClient> QueryAll()
|
||||
{
|
||||
var thisProcess = Process.GetCurrentProcess();
|
||||
|
||||
foreach (var process in Process.GetProcessesByName(thisProcess.ProcessName))
|
||||
{
|
||||
if (process.Id == thisProcess.Id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
IPCClient processChannel = null;
|
||||
|
||||
try
|
||||
{
|
||||
processChannel = new IPCClient(process);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"IPCClient/QueryAll exception: {ex.Message}: {ex.StackTrace} - {ex.InnerException}");
|
||||
// ignored
|
||||
}
|
||||
|
||||
if (processChannel != null)
|
||||
{
|
||||
yield return processChannel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static IPCClient QueryByStatus(InstanceStatus status)
|
||||
{
|
||||
var thisProcess = Process.GetCurrentProcess();
|
||||
|
||||
foreach (var process in Process.GetProcessesByName(thisProcess.ProcessName))
|
||||
{
|
||||
if (process.Id != thisProcess.Id)
|
||||
{
|
||||
IPCClient processChannel = null;
|
||||
try
|
||||
{
|
||||
processChannel = new IPCClient(process);
|
||||
|
||||
if (processChannel.Status == status)
|
||||
{
|
||||
return processChannel;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
processChannel = null;
|
||||
logger.Error(ex, $"IPCClient/QueryByStatus: Couldn't create an IPC Client");
|
||||
Console.WriteLine($"IPCClient/QueryByStatus exception: {ex.Message}: {ex.StackTrace} - {ex.InnerException}");
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,78 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.ServiceModel;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace DisplayMagician.InterProcess
|
||||
{
|
||||
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
|
||||
internal class IPCService : IService
|
||||
{
|
||||
private static ServiceHost _serviceHost;
|
||||
|
||||
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
private IPCService()
|
||||
{
|
||||
Status = InstanceStatus.Busy;
|
||||
}
|
||||
|
||||
public int HoldProcessId { get; set; } = 0;
|
||||
|
||||
public InstanceStatus Status { get; set; }
|
||||
|
||||
public void StopHold()
|
||||
{
|
||||
Application.Exit();
|
||||
}
|
||||
|
||||
public static IPCService GetInstance()
|
||||
{
|
||||
if (_serviceHost != null || StartService())
|
||||
{
|
||||
return _serviceHost?.SingletonInstance as IPCService;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static bool StartService()
|
||||
{
|
||||
if (_serviceHost == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var process = Process.GetCurrentProcess();
|
||||
var service = new IPCService();
|
||||
_serviceHost = new ServiceHost(
|
||||
service,
|
||||
new Uri($"net.pipe://localhost/DisplayMagician_IPC{process.Id}"));
|
||||
|
||||
_serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "Service");
|
||||
_serviceHost.Open();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.Error(ex, $"IPCService/StartService exception: Couldn't create an IPC Service");
|
||||
Console.WriteLine($"IPCService/StartService exception: {ex.Message}: {ex.StackTrace} - {ex.InnerException}");
|
||||
try
|
||||
{
|
||||
_serviceHost?.Close();
|
||||
}
|
||||
catch (Exception ex2)
|
||||
{
|
||||
logger.Error(ex, $"IPCService/StartService exception: Couldn't close an IPC Service after error creating it");
|
||||
Console.WriteLine($"IPCService/StartService exception 2: {ex2.Message}: {ex2.InnerException}");
|
||||
// ignored
|
||||
}
|
||||
|
||||
_serviceHost = null;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
using System.ServiceModel;
|
||||
|
||||
namespace DisplayMagician.InterProcess
|
||||
{
|
||||
[ServiceContract]
|
||||
internal interface IService
|
||||
{
|
||||
int HoldProcessId { [OperationContract] get; }
|
||||
InstanceStatus Status { [OperationContract] get; }
|
||||
|
||||
[OperationContract(IsOneWay = true)]
|
||||
void StopHold();
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
namespace DisplayMagician.InterProcess
|
||||
{
|
||||
internal enum InstanceStatus
|
||||
{
|
||||
User,
|
||||
|
||||
Busy,
|
||||
|
||||
OnHold
|
||||
}
|
||||
}
|
@ -7,7 +7,7 @@ using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using DesktopNotifications;
|
||||
using System.Windows.Forms;
|
||||
using DisplayMagician.InterProcess;
|
||||
//using DisplayMagician.InterProcess;
|
||||
using DisplayMagician.Resources;
|
||||
using DisplayMagicianShared;
|
||||
using DisplayMagician.UIForms;
|
||||
@ -62,6 +62,20 @@ namespace DisplayMagician {
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
|
||||
// Create the remote server if we're first instance, or
|
||||
// If we're a subsequent instance, pass the command line parameters to the first instance and then
|
||||
bool isFirstInstance = SingleInstance.LaunchOrReturn(otherInstance => { MessageBox.Show("got data: " + otherInstance.Skip(1).FirstOrDefault()); }, args);
|
||||
if (isFirstInstance)
|
||||
{
|
||||
Console.WriteLine($"Program/Main: This is the first DisplayMagician to start, so will be the one to actually perform the actions.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"Program/Main: There is already another DisplayMagician running, so we'll use that one to actually perform the actions.");
|
||||
Application.Exit();
|
||||
}
|
||||
|
||||
// If we get here, then we're the first instance!
|
||||
RegisterDisplayMagicianWithWindows();
|
||||
|
||||
// Prepare NLog for internal logging - Comment out when not required
|
||||
@ -85,7 +99,7 @@ namespace DisplayMagician {
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Program/StartUpNormally exception: Cannot create the Application Log Folder {AppLogPath} - {ex.Message}: {ex.StackTrace} - {ex.InnerException}");
|
||||
Console.WriteLine($"Program/Main Exception: Cannot create the Application Log Folder {AppLogPath} - {ex.Message}: {ex.StackTrace} - {ex.InnerException}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -242,27 +256,6 @@ namespace DisplayMagician {
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
|
||||
|
||||
|
||||
if (SingleInstance.InitializeAsFirstInstance("DisplayMagician"))
|
||||
{
|
||||
_syncContext = SynchronizationContext.Current;
|
||||
// Setup Named Pipe listener
|
||||
NamedPipeServerCreateServer();
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// We are not the first instance, send the named pipe message with our payload and stop loading
|
||||
var namedPipeXmlPayload = new Payload
|
||||
{
|
||||
CommandLineArguments = Environment.GetCommandLineArgs().ToList()
|
||||
};
|
||||
|
||||
// Send the message
|
||||
NamedPipeClientSendOptions(namedPipeXmlPayload);
|
||||
return false; // Signal to quit
|
||||
}
|
||||
|
||||
// Check if it's an upgrade from DisplayMagician v1 to v2
|
||||
// and if it is then copy the old configs to the new filenames and
|
||||
// explain to the user what they need to do.
|
||||
@ -688,13 +681,13 @@ namespace DisplayMagician {
|
||||
try
|
||||
{
|
||||
// Start the IPC Service to
|
||||
if (!IPCService.StartService())
|
||||
/*if (!IPCService.StartService())
|
||||
{
|
||||
throw new Exception(Language.Can_not_open_a_named_pipe_for_Inter_process_communication);
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
IPCService.GetInstance().Status = InstanceStatus.User;
|
||||
//IPCService.GetInstance().Status = InstanceStatus.User;
|
||||
|
||||
// Close the splash screen
|
||||
if (ProgramSettings.LoadSettings().ShowSplashScreen && AppSplashScreen != null && !AppSplashScreen.Disposing && !AppSplashScreen.IsDisposed)
|
||||
@ -724,10 +717,10 @@ namespace DisplayMagician {
|
||||
try
|
||||
{
|
||||
// Start the IPC Service to
|
||||
if (!IPCService.StartService())
|
||||
/*if (!IPCService.StartService())
|
||||
{
|
||||
throw new Exception(Language.Can_not_open_a_named_pipe_for_Inter_process_communication);
|
||||
}
|
||||
}*/
|
||||
|
||||
// Create the Shortcut Icon Cache if it doesn't exist so that it's avilable for all the program
|
||||
if (!Directory.Exists(AppIconPath))
|
||||
@ -758,7 +751,7 @@ namespace DisplayMagician {
|
||||
logger.Error(ex, $"Program/StartUpApplication exception create Icon files for future use in {AppIconPath}");
|
||||
}
|
||||
|
||||
IPCService.GetInstance().Status = InstanceStatus.User;
|
||||
//IPCService.GetInstance().Status = InstanceStatus.User;
|
||||
|
||||
// Check for updates
|
||||
CheckForUpdates();
|
||||
@ -806,7 +799,7 @@ namespace DisplayMagician {
|
||||
|
||||
// Check there is only one version of this application so we won't
|
||||
// mess with another monitoring session
|
||||
if (
|
||||
/*if (
|
||||
IPCClient.QueryAll()
|
||||
.Any(
|
||||
client =>
|
||||
@ -816,7 +809,7 @@ namespace DisplayMagician {
|
||||
throw new Exception(
|
||||
Language
|
||||
.Another_instance_of_this_program_is_in_working_state_Please_close_other_instances_before_trying_to_switch_profile);
|
||||
}
|
||||
}*/
|
||||
|
||||
// Match the ShortcutName to the actual shortcut listed in the shortcut library
|
||||
// And error if we can't find it.
|
||||
@ -836,7 +829,7 @@ namespace DisplayMagician {
|
||||
ShortcutRepository.RunShortcut(shortcutToRun);
|
||||
}
|
||||
|
||||
IPCService.GetInstance().Status = InstanceStatus.Busy;
|
||||
//IPCService.GetInstance().Status = InstanceStatus.Busy;
|
||||
|
||||
}
|
||||
|
||||
@ -1221,6 +1214,13 @@ namespace DisplayMagician {
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SignalExternalCommandLineArgs(IList<string> args)
|
||||
{
|
||||
// handle command line arguments of second instance
|
||||
// …
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -2,7 +2,7 @@
|
||||
using AudioSwitcher.AudioApi.CoreAudio;
|
||||
using DisplayMagician.GameLibraries;
|
||||
using DisplayMagician.Processes;
|
||||
using DisplayMagician.InterProcess;
|
||||
//using DisplayMagician.InterProcess;
|
||||
using DisplayMagicianShared;
|
||||
using Microsoft.Toolkit.Uwp.Notifications;
|
||||
using Newtonsoft.Json;
|
||||
|
@ -1,300 +1,226 @@
|
||||
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.Diagnostics;
|
||||
using System.IO.Pipes;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Runtime.Serialization.Json;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace DisplayMagician
|
||||
{
|
||||
/// <summary>
|
||||
/// This class checks to make sure that only one instance of
|
||||
/// this application is running at a time.
|
||||
/// Helper for creating or passing command args to a single application instance
|
||||
/// </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
|
||||
{
|
||||
#region Private Fields
|
||||
/// <summary>
|
||||
/// Unique name to base the single instance decision on. Default's to a hash based on the executable location.
|
||||
/// </summary>
|
||||
public static string UniqueName { get; set; } = "DisplayMagician";
|
||||
|
||||
private static Mutex _mutexApplication;
|
||||
private static readonly object _mutexLock = new object();
|
||||
private static bool _firstApplicationInstance;
|
||||
private static NamedPipeServerStream _namedPipeServerStream;
|
||||
private static SynchronizationContext _syncContext;
|
||||
private static Action<string[]> _otherInstanceCallback;
|
||||
private static readonly object _namedPiperServerThreadLock = new object();
|
||||
|
||||
private static string GetMutexName() => $@"Mutex_{Environment.UserDomainName}_{Environment.UserName}_{UniqueName}";
|
||||
private static string GetPipeName() => $@"Pipe_{Environment.UserDomainName}_{Environment.UserName}_{UniqueName}";
|
||||
|
||||
/// <summary>
|
||||
/// String delimiter used in channel names.
|
||||
/// Determines if the application should continue launching or return because it's not the first instance.
|
||||
/// When not the first instance, the command line args will be passed to the first one.
|
||||
/// </summary>
|
||||
private const string Delimiter = ":";
|
||||
|
||||
/// <summary>
|
||||
/// Suffix to the channel name.
|
||||
/// </summary>
|
||||
private const string ChannelNameSuffix = "DisplayMagicianIPCChannel";
|
||||
|
||||
/// <summary>
|
||||
/// Remote service name.
|
||||
/// </summary>
|
||||
private const string RemoteServiceName = "DisplayMagicianService";
|
||||
|
||||
/// <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
|
||||
/// <param name="otherInstanceCallback">Callback to execute on the first instance with command line args from subsequent launches.
|
||||
/// Will not run on the main thread, marshalling may be required.</param>
|
||||
/// <param name="args">Arguments from Main()</param>
|
||||
/// <returns>true if the first instance, false if it's not the first instance.</returns>
|
||||
public static bool LaunchOrReturn(Action<string[]> otherInstanceCallback, string[] args)
|
||||
{
|
||||
get { return commandLineArgs; }
|
||||
}
|
||||
_otherInstanceCallback = otherInstanceCallback ?? throw new ArgumentNullException(nameof(otherInstanceCallback));
|
||||
|
||||
#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)
|
||||
if (IsApplicationFirstInstance())
|
||||
{
|
||||
CreateRemoteService(channelName);
|
||||
_syncContext = SynchronizationContext.Current;
|
||||
// Setup Named Pipe listener
|
||||
NamedPipeServerCreateServer();
|
||||
return true;
|
||||
}
|
||||
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))
|
||||
// We are not the first instance, send the named pipe message with our payload and stop loading
|
||||
var namedPipeXmlPayload = new Payload
|
||||
{
|
||||
try
|
||||
{
|
||||
using (TextReader reader = new StreamReader(cmdLinePath, System.Text.Encoding.Unicode))
|
||||
{
|
||||
args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
|
||||
}
|
||||
CommandLineArguments = Environment.GetCommandLineArgs().ToList()
|
||||
};
|
||||
|
||||
File.Delete(cmdLinePath);
|
||||
}
|
||||
catch (IOException)
|
||||
// Send the message
|
||||
NamedPipeClientSendOptions(namedPipeXmlPayload);
|
||||
return false; // Signal to quit
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if this is the first instance of this application. Can be run multiple times.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private static bool IsApplicationFirstInstance()
|
||||
{
|
||||
if (_mutexApplication == null)
|
||||
{
|
||||
lock (_mutexLock)
|
||||
{
|
||||
// Allow for multiple runs but only try and get the mutex once
|
||||
if (_mutexApplication == null)
|
||||
{
|
||||
_mutexApplication = new Mutex(true, GetMutexName(), out _firstApplicationInstance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (args == null)
|
||||
return _firstApplicationInstance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Uses a named pipe to send the currently parsed options to an already running instance.
|
||||
/// </summary>
|
||||
/// <param name="namedPipePayload"></param>
|
||||
private static void NamedPipeClientSendOptions(Payload namedPipePayload)
|
||||
{
|
||||
try
|
||||
{
|
||||
args = new string[] { };
|
||||
using (var namedPipeClientStream = new NamedPipeClientStream(".", GetPipeName(), PipeDirection.Out))
|
||||
{
|
||||
namedPipeClientStream.Connect(3000); // Maximum wait 3 seconds
|
||||
|
||||
var ser = new DataContractJsonSerializer(typeof(Payload));
|
||||
ser.WriteObject(namedPipeClientStream, namedPipePayload);
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
catch (Exception)
|
||||
{
|
||||
// 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
|
||||
firstInstanceRemoteServiceReference.InvokeFirstInstance(args);
|
||||
// Error connecting or sending
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Callback for activating first instance of the application.
|
||||
/// Starts a new pipe server if one isn't already active.
|
||||
/// </summary>
|
||||
/// <param name="arg">Callback argument.</param>
|
||||
/// <returns>Always null.</returns>
|
||||
private static object ActivateFirstInstanceCallback(object arg)
|
||||
private static void NamedPipeServerCreateServer()
|
||||
{
|
||||
// Get command line args to be passed to first instance
|
||||
IList<string> args = arg as IList<string>;
|
||||
ActivateFirstInstance(args);
|
||||
return null;
|
||||
// Create a new pipe accessible by local authenticated users, disallow network
|
||||
var sidNetworkService = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null);
|
||||
var sidWorld = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
|
||||
|
||||
var pipeSecurity = new PipeSecurity();
|
||||
|
||||
// Deny network access to the pipe
|
||||
var accessRule = new PipeAccessRule(sidNetworkService, PipeAccessRights.ReadWrite, AccessControlType.Deny);
|
||||
pipeSecurity.AddAccessRule(accessRule);
|
||||
|
||||
// Alow Everyone to read/write
|
||||
accessRule = new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow);
|
||||
pipeSecurity.AddAccessRule(accessRule);
|
||||
|
||||
// Current user is the owner
|
||||
SecurityIdentifier sidOwner = WindowsIdentity.GetCurrent().Owner;
|
||||
if (sidOwner != null)
|
||||
{
|
||||
accessRule = new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow);
|
||||
pipeSecurity.AddAccessRule(accessRule);
|
||||
}
|
||||
|
||||
// Create pipe and start the async connection wait
|
||||
_namedPipeServerStream = new NamedPipeServerStream(
|
||||
GetPipeName(),
|
||||
PipeDirection.In,
|
||||
1,
|
||||
PipeTransmissionMode.Byte,
|
||||
PipeOptions.Asynchronous,
|
||||
0,
|
||||
0,
|
||||
pipeSecurity);
|
||||
|
||||
// Begin async wait for connections
|
||||
_namedPipeServerStream.BeginWaitForConnection(NamedPipeServerConnectionCallback, _namedPipeServerStream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Activates the first instance of the application with arguments from a second instance.
|
||||
/// The function called when a client connects to the named pipe. Note: This method is called on a non-UI thread.
|
||||
/// </summary>
|
||||
/// <param name="args">List of arguments to supply the first instance of the application.</param>
|
||||
private static void ActivateFirstInstance(IList<string> args)
|
||||
/// <param name="iAsyncResult"></param>
|
||||
private static void NamedPipeServerConnectionCallback(IAsyncResult iAsyncResult)
|
||||
{
|
||||
// Set main window state and process command line args
|
||||
if (Application.Current == null)
|
||||
try
|
||||
{
|
||||
// End waiting for the connection
|
||||
_namedPipeServerStream.EndWaitForConnection(iAsyncResult);
|
||||
|
||||
// Read data and prevent access to _namedPipeXmlPayload during threaded operations
|
||||
lock (_namedPiperServerThreadLock)
|
||||
{
|
||||
|
||||
var ser = new DataContractJsonSerializer(typeof(Payload));
|
||||
var payload = (Payload)ser.ReadObject(_namedPipeServerStream);
|
||||
|
||||
// payload contains the data sent from the other instance
|
||||
if (_syncContext != null)
|
||||
{
|
||||
_syncContext.Post(_ => _otherInstanceCallback(payload.CommandLineArguments.ToArray()), null);
|
||||
}
|
||||
else
|
||||
{
|
||||
_otherInstanceCallback(payload.CommandLineArguments.ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// EndWaitForConnection will exception when someone calls closes the pipe before connection made
|
||||
// In that case we dont create any more pipes and just return
|
||||
// This will happen when app is closing and our pipe is closed/disposed
|
||||
return;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Close the original pipe (we will create a new one each time)
|
||||
_namedPipeServerStream.Dispose();
|
||||
}
|
||||
|
||||
((TApplication)Application.Current).SignalExternalCommandLineArgs(args);
|
||||
// Create a new pipe for next connection
|
||||
NamedPipeServerCreateServer();
|
||||
}
|
||||
|
||||
#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
|
||||
/*private static string GetRunningProcessHash()
|
||||
{
|
||||
/// <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)
|
||||
using (var hash = SHA256.Create())
|
||||
{
|
||||
if (Application.Current != null)
|
||||
{
|
||||
// Do an asynchronous call to ActivateFirstInstance function
|
||||
Application.Current.Dispatcher.BeginInvoke(
|
||||
DispatcherPriority.Normal, new DispatcherOperationCallback(SingleInstance<TApplication>.ActivateFirstInstanceCallback), args);
|
||||
}
|
||||
var processPath = Process.GetCurrentProcess().MainModule.FileName;
|
||||
var bytes = hash.ComputeHash(Encoding.UTF8.GetBytes(processPath));
|
||||
return Convert.ToBase64String(bytes);
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
/// <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
|
||||
[DataContract]
|
||||
public class Payload
|
||||
{
|
||||
/// <summary>
|
||||
/// A list of command line arguments.
|
||||
/// </summary>
|
||||
[DataMember]
|
||||
public List<string> CommandLineArguments { get; set; } = new List<string>();
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user