Skip to content

Instantly share code, notes, and snippets.

@manicai
Created January 24, 2014 11:15
Show Gist options
  • Save manicai/8595563 to your computer and use it in GitHub Desktop.
Save manicai/8595563 to your computer and use it in GitHub Desktop.
Noddy C# IPC with WinForms Example
namespace Receiver
{
using System.ServiceModel;
[ServiceContract]
public interface IReceiver
{
[OperationContract]
void AddLine();
}
}
namespace Receiver
{
using System;
using System.Globalization;
using System.ServiceModel;
using System.Windows.Forms;
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public partial class ReceiverForm : Form, IReceiver
{
private readonly Random rng = new Random();
public ReceiverForm()
{
this.InitializeComponent();
}
public void AddLine()
{
var value = this.rng.Next(100).ToString(CultureInfo.InvariantCulture);
this.textBox.Text += value + Environment.NewLine;
}
private void OnButtonClick(object sender, System.EventArgs e)
{
this.AddLine();
}
}
}
namespace Receiver
{
using System;
using System.ServiceModel;
using System.Windows.Forms;
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new ReceiverForm();
using (var host = new ServiceHost(form, new[] { new Uri("net.pipe://localhost") }))
{
host.AddServiceEndpoint(typeof(IReceiver),
new NetNamedPipeBinding(),
"TestReceiver");
try
{
host.Open();
}
catch (AddressAlreadyInUseException ex)
{
return;
}
Application.Run(form);
host.Close();
}
}
}
}
namespace Transmitter
{
using System.ServiceModel;
using System.Windows.Forms;
using Receiver;
public partial class TransmitterForm : Form
{
private IReceiver receiver;
public TransmitterForm()
{
this.InitializeComponent();
var factory = new ChannelFactory<IReceiver>(
new NetNamedPipeBinding(),
new EndpointAddress("net.pipe://localhost/TestReceiver"));
this.receiver = factory.CreateChannel();
}
private void OnButtonClick(object sender, System.EventArgs e)
{
try
{
this.receiver.AddLine();
}
catch (FaultException ex)
{
// Service call failed - possibly because the receiver isn't
// running.
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment