进程间通信,就是这么简单
先看一下代码
辅助类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class ProcessMessage { /// <summary> /// 主程序常量 /// </summary> public static string MainProcessID = "Main"; public static string OtherProcessID = "Test"; /// <summary> /// 消息委托 /// </summary> /// <param name="strmsg">消息</param> public delegate void DelegateMsg(object objmsg, object objfrom); /// <summary> /// 消息事件 /// </summary> public event DelegateMsg OnMsg; /// <summary> /// 功能描述:发送消息到指定进程 /// 作 者:huangzh /// 创建日期:2015-08-26 12:20:50 /// 任务编号: /// </summary> /// <param name="strToolProcessName">进程名</param> /// <param name="objMsg">objMsg</param> public void SendMsgToProcess(string strToolProcessName, object objMsg) { try { ProcessMailBox mail = new ProcessMailBox(strToolProcessName, 1024, true); mail.Content = objMsg; mail.Dispose(); } catch { throw; } } /// <summary> /// 功能描述:从指定进程读取消息 /// 作 者:huangzh /// 创建日期:2015-08-26 12:21:11 /// 任务编号: /// </summary> /// <param name="strToolProcessName">进程名</param> /// <returns>返回值</returns> public void ReadMsgFromProcess(string strToolProcessName) { try { if (OnMsg == null) { throw new Exception("请初始化OnMsg事件"); } Thread th = new Thread(delegate() { IMailBox mail = new ProcessMailBox(strToolProcessName, 1024, false); while (true) { if (OnMsg != null) { OnMsg(mail.Content, strToolProcessName); mail.ClearContent(); } } }); th.IsBackground = true; th.Start(); } catch { throw; } } }
调用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { if (args.Length > 0) { //writer ProcessMessage message = new ProcessMessage(); while (true) { Console.WriteLine("输入内容"); string strmsg = Console.ReadLine(); message.SendMsgToProcess(ProcessMessage.MainProcessID, strmsg); message.SendMsgToProcess(ProcessMessage.OtherProcessID, strmsg); } } else { //reader ProcessMessage message = new ProcessMessage(); message.OnMsg += new ProcessMessage.DelegateMsg(message_OnMsg); message.ReadMsgFromProcess(ProcessMessage.MainProcessID); message.ReadMsgFromProcess(ProcessMessage.OtherProcessID); Console.ReadKey(); } } static void message_OnMsg(object objmsg, object objfrom) { Console.WriteLine("from:[" + objfrom + "]:" + objmsg); } }
再看下效果图
怎么样是不是心动了呢?别慌,往下看
首先辅助类需要一个dll,ThreadMessaging.dll 猛戳我下载这个DLL
然后你就可以华丽丽的使用了,话说这个DLL竟然有源码,如果需要可以留下你的某些联系方式哦
当然,如果你还有其他什么好的建议也可以留下的。
作者:冰封一夏
出处:http://www.cnblogs.com/bfyx/
HZHControls官网:http://www.hzhcontrols.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,
且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
GitHub:https://github.com/kwwwvagaa/NetWinformControl
码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git