欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WinForm实现跨进程通信的方法

程序员文章站 2023-12-21 09:41:52
本文实例展示了winform实现跨进程通信的方法,分享给大家供大家参考之用。具体方法如下: 主要功能代码如下: public class winmessageh...

本文实例展示了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#程序设计有所帮助。

上一篇:

下一篇: