Exemplo n.º 1
0
        /// <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(AppPayload namedPipePayload)
        {
            try
            {
                using (var namedPipeClientStream = new NamedPipeClientStream(".", GetPipeName(), PipeDirection.Out))
                {
                    namedPipeClientStream.Connect(3000); // Maximum wait 3 seconds

                    var ser = new DataContractJsonSerializer(typeof(AppPayload));
                    ser.WriteObject(namedPipeClientStream, namedPipePayload);
                }
            }
            catch (Exception)
            {
                // Error connecting or sending
            }
        }
Exemplo n.º 2
0
        /// <summary>
        ///   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>
        /// <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 IsOnlyInstance(Action <string[]> otherInstanceCallback, string[] args)
        {
            _otherInstanceCallback = otherInstanceCallback ?? throw new ArgumentNullException(nameof(otherInstanceCallback));

            if (IsApplicationFirstInstance())
            {
                _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 AppPayload
                {
                    CommandLineArguments = Environment.GetCommandLineArgs().ToList()
                };

                // Send the message
                NamedPipeClientSendOptions(namedPipeXmlPayload);
                return(false); // Signal to quit
            }
        }