C# 进程消息传递,基于 WPF 测试

服务端


namespace MsgSender
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        //Win32 API函数 
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);
        const int WM_COPYDATA = 0x004A; 
        private void btnSendMsg_Click(object sender, RoutedEventArgs e)
        {
            int hWnd = FindWindow(null, "WUYULE");
            if (hWnd == 0)
            {
                MessageBox.Show("555,未找到消息接受者!");
            }
            else
            {
                byte[] sarr = System.Text.Encoding.Default.GetBytes(tbMsg.Text);
                int len = sarr.Length;
                COPYDATASTRUCT cds;
                cds.dwData = (IntPtr)Convert.ToInt16(tbInt.Text);//可以是任意值 
                cds.cbData = len + 1;//指定lpData内存区域的字节数 
                cds.lpData = tbMsg.Text;//发送给目标窗口所在进程的数据 
                SendMessage(hWnd, WM_COPYDATA, 0, ref cds);
            } 
        }
        //方法1
        //------------------------
        //NamedPipeClientStream pipeClient =
        //    new NamedPipeClientStream("localhost", "testpipe", PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.None);
        //StreamWriter sw = null; 
        //private void btnSendMsgViaPipe_Click(object sender, RoutedEventArgs e)
        //{
        //    Process.Start(@"E:\Code\WPF\WpfApplication3\MsgReceiver\bin\Debug\MsgReceiver.exe");
        //    try
        //    {
        //        if (!pipeClient.IsConnected)
        //        {
        //            pipeClient.Connect(5000);
        //            sw = new StreamWriter(pipeClient);
        //            sw.AutoFlush = true;
        //        }
                          
        //        if (sw != null)
        //        {
        //            sw.WriteLine(this.tbMsg.Text);
        //            this.Close();
        //        }
        //        else
        //        {
        //            MessageBox.Show("未建立连接,不能发送消息。");
        //        } 
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("连接建立失败,请确保服务端程序已经被打开。");
        //        this.Close();
        //    } 
        //} 
        //方法2
        //------------------------------------
        //private void btnSendMsgViaPipe_Click(object sender, RoutedEventArgs e)
        //{
        //    Process.Start(@"E:\Code\WPF\WpfApplication3\MsgReceiver\bin\Debug\MsgReceiver.exe");
        //    using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("testpipe"))
        //    {
        //        pipeStream.WaitForConnection();
        //        using (StreamWriter writer = new StreamWriter(pipeStream))
        //        {
        //            writer.AutoFlush = true;
        //            writer.WriteLine(tbMsg.Text);
        //        }
        //    }
        //}
           
        ////方法3
        ////---------------------------------
        // private void btnSendMsgViaPipe_Click(object sender, RoutedEventArgs e)
        //{
        //    Process process = new Process();
        //    process.StartInfo.FileName = @"E:\Code\WPF\WpfApplication3\MsgReceiver\bin\Debug\MsgReceiver.exe";
        //    //创建匿名管道流实例,
        //    using (AnonymousPipeServerStream pipeStream =
        //        new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
        //    {
        //        //将句柄传递给子进程
        //        process.StartInfo.Arguments = pipeStream.GetClientHandleAsString();
        //        process.StartInfo.UseShellExecute = false;
        //        process.Start();
        //        //销毁子进程的客户端句柄?
        //        pipeStream.DisposeLocalCopyOfClientHandle();
        //        using (StreamWriter sw = new StreamWriter(pipeStream))
        //        {
        //            sw.AutoFlush = true;
        //            //向匿名管道中写入内容
        //            sw.WriteLine(tbMsg.Text);
        //        }
        //    }
        //    process.WaitForExit();
        //    process.Close();
        //}
        //方法4   基于消息传输的命名管道
        //---------------------------------
        private void btnSendMsgViaPipe_Click(object sender, RoutedEventArgs e)
        {
            Process.Start(@"E:\Code\WPF\WpfApplication3\MsgReceiver\bin\Debug\MsgReceiver.exe");
            UTF8Encoding encoding = new UTF8Encoding();
            string message1 = tbMsg.Text;
            string message2 = tbInt.Text;
            Byte[] bytes;
            using (NamedPipeServerStream pipeStream = new
                    NamedPipeServerStream("messagepipe", PipeDirection.InOut, 1,
                    PipeTransmissionMode.Message, PipeOptions.None))
            {
                pipeStream.WaitForConnection();
                // Let’s send two messages.
                bytes = encoding.GetBytes(message1);
                pipeStream.Write(bytes, 0, bytes.Length);
                bytes = encoding.GetBytes(message2);
                pipeStream.Write(bytes, 0, bytes.Length);
            }
        }
    }
}



客户端


namespace MsgReceiver
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += (sender, e) => {
                (PresentationSource.FromVisual(this) as HwndSource).AddHook(new HwndSourceHook(this.WndProc));
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    //方法1
                    //------------------------------------------------
                    //NamedPipeServerStream pipeServer =
                    //  new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                    //pipeServer.BeginWaitForConnection((o) =>
                    //{
                    //    NamedPipeServerStream pServer = (NamedPipeServerStream)o.AsyncState;
                    //    pServer.EndWaitForConnection(o);
                    //    StreamReader sr = new StreamReader(pServer);
                    //    string result = null;
                    //    while (true)
                    //    {
                    //        result = sr.ReadLine();
                    //        if (result != null && result != "bye")
                    //        {
                    //            this.Dispatcher.BeginInvoke(new Action(delegate { lbMsgs.Items.Add(result); }));
                    //        }
                    //        //this.Dispatcher.BeginInvoke(new Action(delegate { lbMsgs.Items.Add(sr.ReadLine()); }));
                    //    }
                    //}, pipeServer);
                    //方法2
                    //-----------------------------
                    //using (NamedPipeClientStream pipeStream = new NamedPipeClientStream("testpipe"))
                    //{
                    //    pipeStream.Connect();
                    //    //在client读取server端写的数据
                    //    using (StreamReader rdr = new StreamReader(pipeStream))
                    //    {
                    //        string temp;
                    //        while ((temp = rdr.ReadLine()) != null && temp != "stop")
                    //        {
                    //            var result = string.Format("{0}:{1}", DateTime.Now, temp);
                    //            this.Dispatcher.BeginInvoke(new Action(delegate { lbMsgs.Items.Add(result); }));
                    //        }
                    //    }
                    //}
                       
                    ////方法3
                    ////-----------------------------------
                    //MessageBox.Show(Environment.GetCommandLineArgs()[1].ToString());
                    //try
                    //{
                    //    using (StreamReader sr = new StreamReader(new AnonymousPipeClientStream(PipeDirection.In, Environment.GetCommandLineArgs()[1])))
                    //    {
                    //        string line;
                    //        while ((line = sr.ReadLine()) != null)
                    //        {
                    //            MessageBox.Show(string.Format("Echo: {0}", line));
                    //        }
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    MessageBox.Show(ex.Message);
                    //}
                    //方法4
                    //-----------------------------------
                    Decoder decoder = Encoding.UTF8.GetDecoder();
                    Byte[] bytes = new Byte[10];
                    Char[] chars = new Char[10];
                    using (NamedPipeClientStream pipeStream =
                            new NamedPipeClientStream("messagepipe"))
                    {
                        pipeStream.Connect();
                        pipeStream.ReadMode = PipeTransmissionMode.Message;
                        int numBytes;
                        do
                        {
                            string message = "";
                            do
                            {
                                numBytes = pipeStream.Read(bytes, 0, bytes.Length);
                                int numChars = decoder.GetChars(bytes, 0, numBytes, chars, 0);
                                message += new String(chars, 0, numChars);
                            } while (!pipeStream.IsMessageComplete);
                            decoder.Reset();
                            if (!string.IsNullOrEmpty(message) && message != "bye")
                            {
                                this.Dispatcher.BeginInvoke(new Action(delegate { lbMsgs.Items.Add(message); }));
                            }
                        } while (numBytes != 0);
                    }
                       
                });
            };
        }
        const int WM_COPYDATA = 0x004A;
        //protected override void OnSourceInitialized(EventArgs e)
        //{
        //    base.OnSourceInitialized(e);
        //    HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
        //    source.AddHook(WndProc);
        //}
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_COPYDATA)
            {
                COPYDATASTRUCT cds = (COPYDATASTRUCT)System.Runtime.InteropServices.Marshal.PtrToStructure(lParam, typeof(COPYDATASTRUCT));
                string strResult = cds.dwData.ToString() + ":" + cds.lpData;
                lbMsgs.Items.Add(strResult); 
            }
            return hwnd;
        }
          
    }
}


知识共享许可协议
《C# 进程消息传递,基于 WPF 测试》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     167.40ms