Friday, March 11, 2011

Interprocess Communication using Named Pipes in C#

Named pipes are a great way to communicate between multiple processes. What's makes them even better is that the processes don't have to share the same language.

A named pipe is a named, one-way or duplex pipe for communication between the pipe server and one or more pipe clients.

Any process can act as both a server and a client, making peer-to-peer communication possible. As used here, the term pipe server refers to a process that creates a named pipe, and the term pipe client refers to a process that connects to an instance of a named pipe. The server-side function for instantiating a named pipe is CreateNamedPipe. The server-side function for accepting a connection is ConnectNamedPipe. A client process connects to a named pipe by using the CreateFile or CallNamedPipe function.


Server Side:
using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.Out))
{
     pipeServer.WaitForConnection();
     try
     {
          using (StreamWriter sw = new StreamWriter(pipeServer))
          {
           sw.AutoFlush = true;
           sw.WriteLine("Mensaje");
           }
     }
     catch (IOException ex)
     {
          MessageBox.Show("ERROR: {0}", ex.Message);
     }
}

Client Side:  
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.In))
{
     try
      {
           pipeClient.Connect(2000);
           using (StreamReader sr = new StreamReader(pipeClient))
           {
                string temp = string.Empty;
                while ((temp = sr.ReadLine()) != null)
           {
           label4.Text = "Received from server: ";
           textBox1.Text = temp;
     }
     catch (Exception ex) { }

Tuesday, March 8, 2011

Show Context Menu on DataGridView

private void gridCoutas_MouseUp(object sender, MouseEventArgs e)
{
          DataGridView.HitTestInfo hitTestInfo;
         if (e.Button == MouseButtons.Right)
          {
            hitTestInfo = gridCoutas.HitTest(e.X, e.Y);

           if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex >= 0)
           {
                ContextMenu RighMenu = new ContextMenu();
                MenuItem Delete = new MenuItem();
                Delete.Text = "Eliminar";
                Delete.Click += (s, ea) =>
                {
                MessageBox.Show(Row.Couta.ToString());
                 };
                RighMenu.MenuItems.Add(Delete);
               RighMenu.Show(gridCoutas, new Point(e.X, e.Y));
          }
    }
}