码迷,mamicode.com
首页 > Windows程序 > 详细

WinForm实现跨进程通信的方法

时间:2017-11-13 23:05:42      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:summary   height   switch   dllimport   use   void   try   lin   orm   

本文实例展示了WinForm实现跨进程通信的方法,分享给大家供大家参考之用。具体方法如下:

主要功能代码如下:

public class WinMessageHelper
{
  private struct COPYDATASTRUCT
  {
    public IntPtr dwData;
    public int cbData;
    [MarshalAs(UnmanagedType.LPStr)]
    public string lpData;
  }
  //使用COPYDATA进行跨进程通信
  public const int WM_COPYDATA = 0x004A;
  [DllImport("User32.dll", EntryPoint = "SendMessage")]
  private static extern int SendMessage(
  int hWnd, // handle to destination window
  int Msg, // message
  int wParam, // first message parameter
  ref COPYDATASTRUCT lParam // second message parameter
  );
  [DllImport("User32.dll", EntryPoint = "FindWindow")]
  private static extern int FindWindow(string lpClassName, string lpWindowName);
  /// <summary>
  /// 发送消息
  /// </summary>
  /// <param name="windowReceiveTitle">接收方窗体标题名称</param>
  /// <param name="strData">要发送的数据</param>
  public static void Send(string windowReceiveTitle, string strData)
  {
    int winHandler = FindWindow(null,windowReceiveTitle);
    if (winHandler != 0)
    {
      byte[] sarr = System.Text.Encoding.Default.GetBytes(strData);
      int len = sarr.Length + 1;
      COPYDATASTRUCT cds;
      cds.dwData = (IntPtr)100;
      cds.lpData = strData;
      cds.cbData = len;
      SendMessage(winHandler, WM_COPYDATA, 0, ref cds);
    }
  }
  /// <summary>
  /// 接收消息
  /// </summary>
  /// <example>
  /// 在窗体中覆盖接收消息函数
  /// protected override void DefWndProc(ref System.Windows.Forms.Message m)
  /// {
  ///   switch(m.Msg)
  ///   {
  ///     case WinMessageHelper.WM_COPYDATA:
  ///       string str = WinMessageHelper.Receive(ref m);
  ///       break;
  ///     default:
  ///       base.DefWndProc(ref m);
  ///       break;
  ///
  ///   }
  /// }
  /// </example>
  /// <returns>接收的到数据</returns>
  public static string Receive(ref System.Windows.Forms.Message m)
  {
    COPYDATASTRUCT cds = new COPYDATASTRUCT();
    Type cdsType = cds.GetType();
    cds = (COPYDATASTRUCT)m.GetLParam(cdsType);
    return cds.lpData;
  }
}

希望本文所述实例对大家C#程序设计有所帮助。

除声明外,跑步客文章均为原创,转载请以链接形式标明本文地址
  WinForm实现跨进程通信的方法

本文地址:  http://www.paobuke.com/develop/c-develop/pbk23590.html






相关内容

WinForm实现跨进程通信的方法

标签:summary   height   switch   dllimport   use   void   try   lin   orm   

原文地址:http://www.cnblogs.com/paobuke/p/7828225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!