WPF IPC通信

索引サイト
そんなこんなでプロセス間通信が必要になったので

参考:http://gurizuri0505.halfmoon.jp/develop/csharp/processmessage
(参照設定) System.Runtime.Remoting
IPC 定義↓




namespace RemoteTranceObject
{
public class ClassCommandInfo : MarshalByRefObject
{
public class ClassCommandInfoEventArg : EventArgs
{
private int m_cube = 0;
private string m_command = null;

public int Cube { get { return m_cube; } set { m_cube = value; } }
public string Command { get { return m_command; } set { m_command = value; } }

public ClassCommandInfoEventArg(int c_cube, string c_command)
{
m_cube = c_cube;
m_command = c_command;
}
}

public delegate void CallEventHandler(ClassCommandInfoEventArg e);
public event CallEventHandler OnTrance;

public void DataTrance(int p_int16, string p_command)
{
if (OnTrance != null)
{
OnTrance(new ClassCommandInfoEventArg(p_int16, p_command));
}
}
}
}

受信↓




using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using RemoteTranceObject;

namespace WpfApplication1
{
///


/// MainWindow.xaml の相互作用ロジック
///

public partial class MainWindow : Window
{
private ClassCommandInfo z_receiveMessage = null;

public MainWindow()
{
InitializeComponent();
initIPC();
}
private void initIPC()
{
IpcServerChannel servChannel = new IpcServerChannel("ProcessTrance");
ChannelServices.RegisterChannel(servChannel, true);

textBlock1.Text = servChannel.GetChannelUri();

z_receiveMessage = new ClassCommandInfo();
z_receiveMessage.OnTrance += new ClassCommandInfo.CallEventHandler(ipc_Receive);

RemotingServices.Marshal(z_receiveMessage, "command", typeof(ClassCommandInfo));
}
private void ipc_Receive(ClassCommandInfo.ClassCommandInfoEventArg e)
{
string w_cube = Convert.ToString(e.Cube);
MessageBox.Show("cube-->" + w_cube + " command-->" + e.Command);
}
}
}

送信↓




using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using RemoteTranceObject;

namespace WpfApplication1
{
///


/// MainWindow.xaml の相互作用ロジック
///

public partial class MainWindow : Window
{
Int16 z_cubeNumber = 0;
private ClassCommandInfo z_sendMessage = null;

public MainWindow()
{
InitializeComponent();
initIPC();
z_cubeNumber = 1;
}
private void initIPC()
{
IpcClientChannel clientChannel = new IpcClientChannel();
ChannelServices.RegisterChannel(clientChannel, true);
z_sendMessage = (ClassCommandInfo)Activator.GetObject(typeof(ClassCommandInfo), "ipc://ProcessTrance/command");

}
private void button1_Click(object sender, RoutedEventArgs e)
{
string st = textBox1.Text;
try
{
z_sendMessage.DataTrance(z_cubeNumber, st);
}
catch
{
MessageBox.Show("通信エラー");
}
}
}
}



AX