Example #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            while (true)
            {
                using (var clientStream = new System.IO.Pipes.NamedPipeClientStream("127.0.0.1", "NamedPipeServerStream_Test"))
                {
                    Console.WriteLine("before Connect()");
                    clientStream.Connect(1000);
                    clientStream.ReadMode = System.IO.Pipes.PipeTransmissionMode.Message;

                    do
                    {
                        byte[] bytes = new byte[4];
                        clientStream.Read(bytes, 0, 4);
                        int val = BitConverter.ToInt32(bytes, 0);
                        Console.WriteLine("NewID == " + val + "\r");
                    } while (!clientStream.IsMessageComplete);
                }

                Thread.Sleep(1);
            }
            ;
        }
Example #2
0
        //========================
        // メンバーメソッド
        //========================



        //============
        // サーバー接続
        // 本メソッドで、サーバーへの接続を行ないます。
        // 第1引数: サーバーへ要求するコマンド(命令)
        public bool Connect(string Command_Message)
        {
            try
            {
                // 名前付きパイプ操作用のオブジェクト(クライアント用)を生成
                pipeClient = new System.IO.Pipes.NamedPipeClientStream(".", "acsl-pipe", System.IO.Pipes.PipeDirection.InOut);


                // サーバー接続
                // --- 待機中のサーバーに接続します。
                //pipeClient.Connect();
                pipeClient.Connect(5000);

                // サーバーへ送るコマンドを保存
                CommandMessage = Command_Message;


                // 接続通知受信
                ReceiveConnectionNotice(this);

                //System.Windows.MessageBox.Show("データを転送に成功しました。");
                return(true);
            }
            catch
            {
                System.Windows.MessageBox.Show("データを転送に失敗しました。");
                return(false);
            }
        }
Example #3
0
        public void start(string pipe)
        {
            System.IO.Pipes.NamedPipeClientStream client = new System.IO.Pipes.NamedPipeClientStream(".", pipe, System.IO.Pipes.PipeDirection.Out, System.IO.Pipes.PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.Delegation);
            client.Connect();

            // Write some data (doesn't matter what)
            client.Write(new byte[] { 0x40, 0x5f, 0x78, 0x70, 0x6e, 0x5f }, 0, 6);
        }
Example #4
0
        public void start(string pipe)
        {
            System.IO.Pipes.NamedPipeClientStream client = new System.IO.Pipes.NamedPipeClientStream(".", pipe, System.IO.Pipes.PipeDirection.Out, System.IO.Pipes.PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.Delegation);
            client.Connect();

            // Write some data (doesn't matter what)
            client.Write(new byte[] { 0x40, 0x5f, 0x78, 0x70, 0x6e, 0x5f }, 0, 6);
        }
Example #5
0
 protected override void ProcessRecord()
 {
     System.IO.Pipes.NamedPipeClientStream Pipe;
     Pipe = new System.IO.Pipes.NamedPipeClientStream(Server, Name);
     Pipe.Connect();
     Test.cmdlets.Server.ReadDelimiter = Delimiter;
     WriteObject(Pipe);
 }
 public Notifier Shutdown()
 {
     if (this._clientPipe != null)
     {
         this._clientPipe.Close();
         this._clientPipe = null;
     }
     return(this);
 }
        public static Notifier NotifyReadyToClient(string pipeName)
        {
            var clientPipe =
                new System.IO.Pipes.NamedPipeClientStream(
                    ".", pipeName, System.IO.Pipes.PipeDirection.InOut);

            clientPipe.Connect();
            return(new Notifier(clientPipe));
        }
Example #8
0
 private ErrCode SendPipe(CtrlCmd param, MemoryStream send, ref MemoryStream res)
 {
     lock (thisLock)
     {
         // 接続待ち
         try
         {
             using (var waitEvent = System.Threading.EventWaitHandle.OpenExisting(eventName,
                                                                                  System.Security.AccessControl.EventWaitHandleRights.Synchronize))
             {
                 if (waitEvent.WaitOne(connectTimeOut) == false)
                 {
                     return(ErrCode.CMD_ERR_TIMEOUT);
                 }
             }
         }
         catch (System.Threading.WaitHandleCannotBeOpenedException)
         {
             return(ErrCode.CMD_ERR_CONNECT);
         }
         // 接続
         using (var pipe = new System.IO.Pipes.NamedPipeClientStream(pipeName))
         {
             pipe.Connect(0);
             // 送信
             var head = new byte[8];
             BitConverter.GetBytes((uint)param).CopyTo(head, 0);
             BitConverter.GetBytes((uint)(send == null ? 0 : send.Length)).CopyTo(head, 4);
             pipe.Write(head, 0, 8);
             if (send != null && send.Length != 0)
             {
                 send.Close();
                 byte[] data = send.ToArray();
                 pipe.Write(data, 0, data.Length);
             }
             // 受信
             if (pipe.Read(head, 0, 8) != 8)
             {
                 return(ErrCode.CMD_ERR);
             }
             uint resParam = BitConverter.ToUInt32(head, 0);
             var  resData  = new byte[BitConverter.ToUInt32(head, 4)];
             for (int n = 0; n < resData.Length;)
             {
                 int m = pipe.Read(resData, n, resData.Length - n);
                 if (m <= 0)
                 {
                     return(ErrCode.CMD_ERR);
                 }
                 n += m;
             }
             res = new MemoryStream(resData, false);
             return(Enum.IsDefined(typeof(ErrCode), resParam) ? (ErrCode)resParam : ErrCode.CMD_ERR);
         }
     }
 }
Example #9
0
 public static object[] NamedPipeCreate(string name)
 {
     System.IO.Pipes.NamedPipeClientStream pipe = new System.IO.Pipes.NamedPipeClientStream(name);
     pipe.Connect();
     return(new object[] {
         pipe,
         new System.IO.StreamReader(pipe),
         new System.IO.StreamWriter(pipe),
     });
 }
Example #10
0
        public IPCBus(string path)
        {
            _downstream = new System.IO.Pipes.NamedPipeClientStream("com.h3m3.posix.sockets." + System.Diagnostics.Process.GetCurrentProcess().Id);
            _upstream   = new System.IO.Pipes.NamedPipeServerStream("com.h3m3.posix.sockets.SockServ");
            System.IO.Pipes.PipeSecurity downstreamACL = new System.IO.Pipes.PipeSecurity();

            downstreamACL.AddAccessRule(new System.IO.Pipes.PipeAccessRule(Environment.UserName, System.IO.Pipes.PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));

            _downstream.SetAccessControl(downstreamACL);
        }
Example #11
0
        /// <summary>
        /// Try write message to named pipe
        /// </summary>
        /// <param name="text">text to send</param>
        public void TryWritePipe(string text)
        {
            if (!EnableSharedOutput)
            {
                return;
            }
            if (text == null || text == "")
            {
                return;
            }

            string name = "";

            if (Name == null || Name.Trim() == "")
            {
                name = "NetOffice.DebugConsole";
            }
            else
            {
                name = "NetOffice.DebugConsole." + Name;
            }

            try
            {
                using (System.IO.Pipes.NamedPipeClientStream pipe =
                           new System.IO.Pipes.NamedPipeClientStream(name))
                {
                    pipe.Connect(500);
                    using (StreamWriter writer = new StreamWriter(pipe))
                    {
                        writer.WriteLine(text);
                    }
                }
            }
            catch (TimeoutException exception)
            {
                if (RaisePipeError(name, text, exception))
                {
                    EnableSharedOutput = false;
                }
            }
            catch (Exception exception)
            {
                AddToMessageList("Failed to send shared message.", MessageKind.Warning);
                if (RaisePipeError(name, text, exception))
                {
                    EnableSharedOutput = false;
                }
            }
        }
Example #12
0
        public byte[] HeaderBuffer;         // ヘッダー



        //============
        // コンストラクタ
        // 第1引数: 制御対象のストリーム
        public PipeClient()
        {
            // Int32型のデーターのサイズ(Int32型サイズ)
            Int32 Int_Size = sizeof(Int32);


            // Int32型データー用バイト型配列
            // 後にint型データーを、バイト型配列に格納する時に使う。
            HeaderBuffer = new byte[Int_Size];


            // パイプストリームとタイマーの初期化(解法状態で初期化)
            this.pipeClient = null;
        }
Example #13
0
 private static void PostIpcCmd(string cmd)
 {
     using (var pipeClient = new System.IO.Pipes.NamedPipeClientStream("WGestures_IPC_API"))
     {
         pipeClient.Connect();
         using (var writer = new StreamWriter(pipeClient)
         {
             AutoFlush = true
         })
         {
             writer.WriteLine(cmd);
         }
     }
 }
Example #14
0
        static void ActivateAnotherInstance(string npname)
        {
            using (var nps = new System.IO.Pipes.NamedPipeClientStream(".", npname
                                                                       , System.IO.Pipes.PipeDirection.InOut, System.IO.Pipes.PipeOptions.Asynchronous | System.IO.Pipes.PipeOptions.WriteThrough
                                                                       , System.Security.Principal.TokenImpersonationLevel.Anonymous))
            {
                MemoryStream ms = new MemoryStream();
                try
                {
                    nps.Connect(2000);

                    byte[] buffer = new byte[1024];
                    while (nps.IsConnected)
                    {
                        int rc;
                        try
                        {
                            rc = nps.Read(buffer, 0, buffer.Length);
                        }
                        catch (IOException)
                        {
                            break;
                        }
                        if (rc == 0)
                        {
                            Thread.Sleep(10);
                            continue;
                        }
                        WriteDebugLine("read data size " + rc);
                        if (rc != 0)
                        {
                            ms.Write(buffer, 0, rc);
                        }
                    }

                    nps.Close();
                }
                catch (Exception x)
                {
                    WriteDebugLine(x);
                }
                string msg = System.Text.Encoding.ASCII.GetString(ms.ToArray());
                WriteDebugLine("ActivateAnotherInstance " + msg);
            }
        }
Example #15
0
 /// <summary>
 /// Tries to load a project in another process.
 /// </summary>
 private static bool SendProjectLoadRequest(String appName, String projectName, String projectPath)
 {
     try
     {
         using (System.IO.Pipes.NamedPipeClientStream stream = new System.IO.Pipes.NamedPipeClientStream(".", appName + "_Pipe", System.IO.Pipes.PipeDirection.Out))
         {
             stream.Connect(300);
             using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream))
             {
                 writer.AutoFlush = true;
                 writer.WriteLine(projectName);
                 writer.WriteLine(projectPath);
                 return(true);
             }
         }
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #16
0
        public override async void Start(FrameBase frameBase)
        {
            var frame = frameBase as RequestFrame;

            if (frame == null)
            {
                return;
            }

            AnswerFrame answerFrame = new AnswerFrame(frame.Guid);

            try
            {
                string pipeName = Guid.NewGuid().ToString();
                if (!Tools.Session.CreateProcess(Tools.Program.CommandlineCamera(pipeName, 5000), Environment.CurrentDirectory))
                {
                    throw new Exception("无法创建捕获进程。");
                }

                using (System.IO.Pipes.NamedPipeClientStream pipeStream = new System.IO.Pipes.NamedPipeClientStream(pipeName))
                    using (MemoryStream ms = new MemoryStream())
                    {
                        pipeStream.Connect(2000);
                        await pipeStream.CopyToAsync(ms).ConfigureAwait(false);

                        answerFrame.BytesJpeg = ms.ToArray();

                        if (answerFrame.BytesJpeg.Length == 0)
                        {
                            throw new Exception("当前环境不支持此操作。");
                        }
                        await SendFrame(answerFrame).ConfigureAwait(false);
                    }
            }
            catch (Exception ex)
            {
                await SendError(frame, ex.Message).ConfigureAwait(false);
            }
        }
Example #17
0
        } // GiveFeedbackToUiInput

        private void NavigateItemsPool(object itmCategory, object itmSource, string command)
        {
            try
            {
                string verbose = $"Processing command '{command}' for category '{itmCategory.ToString()}' and source '{itmSource.ToString()}' ... ";
                WriteVerbose(verbose);

                string itemCategory = itmCategory.ToString();
                string itemSource   = itmSource.ToString();

                if (null == Pipe)
                {
                    Pipe = new System.IO.Pipes.NamedPipeClientStream
                           (
                        ServerPipeName, ClientPipeName,
                        System.IO.Pipes.PipeDirection.InOut,
                        System.IO.Pipes.PipeOptions.Asynchronous
                           );
                }

                if (!Pipe.IsConnected)
                {
                    verbose = "Pipe is not connected. Connecting ... ";
                    WriteVerbose(verbose, true);
                    try
                    {
                        Pipe.Connect(1000);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine
                        (
                            "NavigateItemsPool: " + ex.Message
                        );
                    }
                }

                if (Pipe.IsConnected)
                {
                    verbose = "OK";
                    WriteVerbose(verbose, false, "Green");

                    string message = command + PipeMessageSeparator +
                                     itemCategory + PipeMessageSeparator +
                                     itemSource;

                    var buffer = Encoding.GetBytes(message);
                    var task   = Pipe.WriteAsync(buffer, 0, 1);

                    string operation = $"'{command}' on '{itemCategory}' from '{itemSource}'";
                    PipeWriteAsyncReturn(task, operation, this);
                }
                else
                {
                    verbose = "ERROR";
                    WriteVerbose(verbose, false, "Red");
                    string message = $"Status: Pipe not connected\r\n" +
                                     $"Command '{command}' on '{itemCategory}' from '{itemSource}'";
                    WriteFeedback(message, this);
                }

                verbose = "Done Processing";
                WriteVerbose(verbose, false, "Green");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("NavigateItemsPool: " + ex.Message);
            }
            finally
            {
            }
        } // NavigateItemsPool
Example #18
0
        static void Main(string[] args)
        {
#if DEBUG
            for (int i = 0; i < 100; ++i)
            {
                if (!System.Diagnostics.Debugger.IsAttached)
                {
                    System.Threading.Thread.Sleep(100);
                }
            }
#endif
            Console.WriteLine("Started");

            var pipeName = "";
            if (args != null && args.Length > 0)
            {
                pipeName = args[0];
            }
            if (pipeName == null)
            {
                pipeName = "";
            }

            using (var pipein = new System.IO.Pipes.NamedPipeClientStream(".", "ProgressShowerInConsole" + pipeName, System.IO.Pipes.PipeDirection.In))
            {
                using (var pipeout = new System.IO.Pipes.NamedPipeClientStream(".", "ProgressShowerInConsoleControl" + pipeName, System.IO.Pipes.PipeDirection.Out))
                {
                    pipein.Connect();
                    pipeout.Connect();
                    Console.WriteLine("Connected");

                    var thd_Read = new System.Threading.Thread(() =>
                    {
                        try
                        {
                            var sr = new System.IO.StreamReader(pipein);
                            while (true)
                            {
                                var line = sr.ReadLine();
                                if (line == "\uEE05Message")
                                {
                                    var mess = sr.ReadLine();
                                    Console.WriteLine(mess);
                                }
                                else if (line == "\uEE05Title")
                                {
                                    var title     = sr.ReadLine();
                                    Console.Title = title;
                                    Console.WriteLine("Showing progress of " + title);
                                }
                                else if (line == "\uEE05Quit")
                                {
                                    break;
                                }
                            }
                        }
                        finally
                        {
                            Console.WriteLine("Closing...");
                            System.Threading.Thread.Sleep(3000);
                        }
                    });
                    thd_Read.Start();

                    var thd_Control = new System.Threading.Thread(() =>
                    {
                        try
                        {
                            var sw = new System.IO.StreamWriter(pipeout);
                            while (true)
                            {
                                var kinfo = Console.ReadKey(true);
                                if (kinfo.Key == ConsoleKey.Q && (kinfo.Modifiers & ConsoleModifiers.Control) != 0)
                                {
                                    sw.WriteLine("\uEE05Quit");
                                    sw.Flush();
                                    break;
                                }
                            }
                        }
                        finally
                        {
                            thd_Read.Abort();
                        }
                    });
                    thd_Control.Start();

                    thd_Read.Join();
                    Environment.Exit(0);
                }
            }
        }
Example #19
0
        public void StreamDataExchange_Pipes()
        {
            bool success   = false;
            bool completed = false;

            int    size    = 200000000;
            string message = GenerateMessage(size);

            var client = new System.IO.Pipes.NamedPipeClientStream("TESTPIPE");
            var server = new System.IO.Pipes.NamedPipeServerStream("TESTPIPE");

            var banchmarkTimer = new System.Diagnostics.Stopwatch();

            banchmarkTimer.Start();

            var reading = new Task(async delegate()
            {
                await client.ConnectAsync();

                try
                {
                    // Data to message format.
                    string receivedMessage = await StreamHandler.StreamReaderAsync <string>(client);

                    // Stoping banchmark.
                    banchmarkTimer.Stop();

                    // Validate data.
                    success   = receivedMessage.Equals(message);
                    completed = true;
                }
                catch (Exception ex)
                {
                    Assert.Fail(ex.Message);
                    return;
                }
            });

            var writing = new Task(async delegate()
            {
                // Wait client connection.
                await server.WaitForConnectionAsync();

                try
                {
                    // Sending message to stream.
                    await StreamHandler.StreamWriterAsync(server, message);
                }
                catch (Exception ex)
                {
                    Assert.Fail(ex.Message);
                    return;
                }
            });


            reading.Start();
            writing.Start();

            while (!completed)
            {
                Thread.Sleep(5);
            }

            float secondsFromStart = banchmarkTimer.ElapsedMilliseconds / (1000.0f);
            float sharedMBSize     = size / 1000000.0f;
            float speedMBpS        = sharedMBSize / secondsFromStart;

            Console.WriteLine("Transmission time: " + secondsFromStart + " seconds");
            Console.WriteLine("Transmisted: " + sharedMBSize + " MB");
            Console.WriteLine("Speed: " +
                              speedMBpS + " MB/s | " +
                              (speedMBpS * 8) + "Mb/s");


            client.Dispose();
            server.Dispose();

            Assert.IsTrue(success);
        }
Example #20
0
        public Editor()
        {
            InitializeComponent();
             this.WindowState = FormWindowState.Maximized;
             m_CurrentDirectory = Directory.GetCurrentDirectory();
             m_AssetsDirectory = m_CurrentDirectory + "\\Assets\\";

             m_SupportEditorPattern = new List<string>(){ "*.xml",
                                                "*.fragmentshader",
                                                "*.vertexshader",
                                                "*.lua"};
             for ( int i = 0; i < m_SupportEditorPattern.Count; i++)
            {
            m_SupportEditorPattern[i] = WildCardToRegular( m_SupportEditorPattern[i] );
            }

             // Setting all of splitter width in all comtainers
             int splitterWidth = 10;
             this.splitContainer1.SplitterWidth = splitterWidth;
             this.splitContainer2.SplitterWidth = splitterWidth;
             this.splitContainer_Left.SplitterWidth = splitterWidth;
             this.splitContainer_Mid.SplitterWidth = splitterWidth;
             this.splitContainer_Right.SplitterWidth = splitterWidth;

             int SDLWindowWidth = 1366;
             int SDLWindowHeight = 768;
             int lrPageWidth = ( this.splitContainer1.Width - SDLWindowWidth - 2 * splitterWidth - 8 ) / 2;
             this.splitContainer1.SplitterDistance = this.splitContainer1.Width - lrPageWidth - splitterWidth - 4;
             this.splitContainer2.SplitterDistance = this.splitContainer2.Width - SDLWindowWidth - splitterWidth;
             this.splitContainer_Mid.SplitterDistance = SDLWindowHeight;

             InitializeAssetTree();

             m_RedirectStringDelegate = new strDelegate( RedirectString );
             m_SetActorDataStringDelegate = new strDelegate( SetActorDataGrid );

             TextBoxWritter textBoxWritter = new TextBoxWritter( this.textBox_Console );
             Console.SetOut( textBoxWritter );

             Console.WriteLine( "Initializing output redirecting" );
             int id = System.Diagnostics.Process.GetCurrentProcess().Id; // make this instance unique
             m_ServerPipe = new System.IO.Pipes.NamedPipeServerStream( "consoleRedirect" + id, System.IO.Pipes.PipeDirection.In, 1 );
             m_ClientPipe = new System.IO.Pipes.NamedPipeClientStream( ".", "consoleRedirect" + id, System.IO.Pipes.PipeDirection.Out, System.IO.Pipes.PipeOptions.WriteThrough );
             m_ClientPipe.Connect();
             System.Runtime.InteropServices.HandleRef hr11 = new System.Runtime.InteropServices.HandleRef( m_ClientPipe, m_ClientPipe.SafePipeHandle.DangerousGetHandle() );
             SetStdHandle( -11, hr11.Handle ); // redirect stdout to my pipe
             SetStdHandle( -12, hr11.Handle ); // redirect error to my pipe
             Console.WriteLine( "Waiting for console connection" );
             m_ServerPipe.WaitForConnection(); //blocking
             Console.WriteLine( "Console connection complete." );

             m_DllRedirectThreadWorker = new DllRedirectThreadObject();
             m_DllRedirectThreadWorker.SetReader( m_ServerPipe );
             m_DllRedirectThread = new Thread( m_DllRedirectThreadWorker.Run );
             m_DllRedirectThread.Start();

             m_SDLThreadWorker = new SDLThreadObject( Handle, this.tabPageEX_World.Handle, this.splitContainer_Mid.Panel1.Width, this.splitContainer_Mid.Panel1.Height );
             m_SDLThread = new Thread( m_SDLThreadWorker.Run );
             m_SDLThread.Start();
        }
Example #21
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            System.IO.Pipes.NamedPipeClientStream MIDIPipe = new System.IO.Pipes.NamedPipeClientStream("MIDIPipe");
            MIDIPipe.Connect();

            int MIDI = 0;
            while ((MIDI = MIDIPipe.ReadByte()) > 0)
            {
                if ((MIDI & 0xF0) == 0x90)//NoteOn
                {
                    UtilityAudio.MIDI_NoteOn((byte)MIDIPipe.ReadByte(), (byte)MIDIPipe.ReadByte());
                }
            }
        }
Example #22
0
 private static void Thread()
 {
     string PipeName = XervBackup.Scheduler.Utility.NamedPipeServerStream.MakePipeName(Program.PipeBaseName, XervBackup.Scheduler.Utility.User.UserName, System.IO.Pipes.PipeDirection.In);
     while (true)
     {
         lock (Locker) itsPipe = new System.IO.Pipes.NamedPipeClientStream(".", PipeName, System.IO.Pipes.PipeDirection.Out);
         Debug.WriteLine("Looking for out pipe: " + PipeName);
         using (itsPipe)
         {
             try { itsPipe.Connect(5000); }
             catch (Exception Ex)
             {
                 Debug.WriteLine(Ex);
             }
             Debug.WriteLine("Connected = " + itsPipe.IsConnected.ToString());
             if (itsPipe.IsConnected)
             {
                 using (itsPipeWriter = new System.IO.StreamWriter(itsPipe) { AutoFlush = true })
                 {
                     try
                     {
                         while (itsPipe.IsConnected)
                             System.Threading.Thread.Sleep(1000);
                     }
                     catch { }    // It's a broken pipe...
                 }
             }
             // itsPipe.Close();
         }
     }
 }
 private Notifier(System.IO.Pipes.NamedPipeClientStream clientPipe)
 {
     this._clientPipe = clientPipe;
 }
Example #24
0
        static void Main(string[] args)
        {
            //------------------------------------
            //  Allowing only one instance
            //------------------------------------

            try
            {
                //  Create the mutex, other instances will not be able to create launch the app again
                using (Mutex mutex = new Mutex(true, @"PDS1_FileShare"))
                {
                    //  Wait 0 seconds, which means: just check if I could get the mutex
                    if (mutex.WaitOne(TimeSpan.Zero, true))
                    {
                        //  Got the mutex? It means it wasn't owned by anybody.
                        //  Let's start the application
                        App app = new App();
                        app.Run();

                        //  Wait for the workers to finish before dying (actually, at this point they are already dead.)
                        app.MulticastWorker.Wait();
                        app.SendToWorker.Wait();
                        app.ConnectionsListenerWorker.Wait();

                        //  "Why setting as null if it is disposed? The app is going to die anyway!"
                        //  Well, if you don't do it, the app's taskbar icon will stay there until you hover your mouse on it.
                        //  Weird, isn't it?
                        app.TaskbarIcon.Dispose();
                        app.TaskbarIcon = null;

                        //  I wrapped the mutex with using, do I really need to do this?
                        //  Doesn't .Disclose() already do this?
                        mutex.ReleaseMutex();
                    }

                    //  If I didn't get the lock, it means I am a second instance.
                    //  NOTE: if you're here, it means that you are a new process, so we have to communicate
                    //  with the main process! I'll do that with a NamedPipe, see SendToWorker for details.
                    else
                    {
                        //  No args?
                        if (args.Length < 1)
                        {
                            MessageBox.Show("Error!", "Only one instance at a time is allowed.", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }

                        //  First arg is invalid?
                        if (args[0].Length < 1)
                        {
                            MessageBox.Show("Error!", "The file is invalid.", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }

                        //------------------------------------
                        //  Notify the SendToWorker
                        //------------------------------------

                        //  SendToWorker is waiting for the user to tell it to send something,
                        //  we are going to act as clients here.
                        using (System.IO.Pipes.NamedPipeClientStream client =
                                   new System.IO.Pipes.NamedPipeClientStream(".", "pds_sendto", System.IO.Pipes.PipeDirection.Out))
                        {
                            client.Connect();

                            if (client.CanWrite)
                            {
                                byte[] arg = Encoding.Unicode.GetBytes(args[0]);
                                client.Write(arg, 0, arg.Length);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error!", "An error occurred while trying to run the app.", MessageBoxButton.OK, MessageBoxImage.Error);
                //Debug.WriteLine(e.Message);
            }
        }
Example #25
0
 private static void PostIpcCmd(string cmd)
 {
     using (var pipeClient = new System.IO.Pipes.NamedPipeClientStream("WGestures_IPC_API"))
     {
         pipeClient.Connect();
         using (var writer = new StreamWriter(pipeClient) { AutoFlush = true })
         {
             writer.WriteLine(cmd);
         }
     }
 }
Example #26
0
 public ICommunicationConnection Connect(ICommunicationInitialisation initArgs)
 {
     System.IO.Pipes.NamedPipeClientStream client = new System.IO.Pipes.NamedPipeClientStream(((NamedPipeInitialisation)initArgs).PipeId);
     client.Connect();
     return new NamedPipeConnection(client);
 }
Example #27
0
 public ICommunicationConnection Connect(ICommunicationInitialisation initArgs)
 {
     System.IO.Pipes.NamedPipeClientStream client = new System.IO.Pipes.NamedPipeClientStream(((NamedPipeInitialisation)initArgs).PipeId);
     client.Connect();
     return(new NamedPipeConnection(client));
 }
Example #28
0
        } // WriteFeedback

        private Task ReadConfigurationData()
        {
            Task task = Task.Factory.StartNew(new Action(() =>
            {
                try
                {
                    string ConfigData = System.String.Empty;
                    int size          = 4096;
                    var buffer        = new byte[size];

                    do
                    {
                        if (null == Pipe)
                        {
                            Pipe = new System.IO.Pipes.NamedPipeClientStream
                                   (
                                ServerPipeName, ClientPipeName,
                                System.IO.Pipes.PipeDirection.InOut,
                                System.IO.Pipes.PipeOptions.Asynchronous
                                   );
                        }

                        if (!Pipe.IsConnected)
                        {
                            try
                            {
                                Pipe.Connect(1000);
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine
                                (
                                    "ReadConfigurationData: " + ex.Message
                                );
                            }
                        }

                        if (Pipe.IsConnected)
                        {
                            var T = Pipe.ReadAsync(buffer, 0, 1);
                            if (T.IsCompleted)
                            {
                                ConfigData = Encoding.GetString(buffer);
                                if (System.String.IsNullOrEmpty(ConfigData))
                                {
                                    continue;
                                }

                                if (ConfigData.StartsWith("Configuration", StringComparison.OrdinalIgnoreCase))
                                {
                                    // Use configuration data
                                }
                                else
                                {
                                    // Clean buffer
                                    for (int i = 0; i < buffer.Count(); i++)
                                    {
                                        buffer[i] = Encoding.GetBytes("0")[0];
                                    }
                                    ConfigData = System.String.Empty;
                                }
                            }
                        }
                        else // Could not connect
                        {
                        }
                    }while (System.String.IsNullOrEmpty(ConfigData));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("ReadConfigurationData: " + ex.Message);
                }
            }));

            return(task);
        } // ReadConfigurationData