使用Windows API实现两个进程间(含窗体)的通信在Windows下的两个进程之间通信通常有多种实现方式,在.NET中,有如命名管道、消息队列、共享内存等实现方式,这篇文章要讲的是使用Windows的API来实现简单的进程间通信,这两个进程既可以都是基于C#开发,也可以都是基于C++开发,也可以是一个C#开发而另一个为C++开发,在C++开发方面,不需要额外调用Windows的API,而是可以直接使用相关方法即可。所以,这里重点要讲的就是在C#中是如何做的,而至于在C++中是如何做的将给出例子,并不做详述。

对于接收消息,只需要重写DefWndProc函数即可,对于发送消息,笔者编写了一个类MsgHandler来实现。要顺利实现消息的接收与发送,使用了Windows的API:FindWindow、SendMessage等。在C#环境中,通过DllImport来引入相应的API,代码示例如下:

// FindWindow method, using Windows API
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);

// IsWindow method, using Windows API
[DllImport("User32.dll", EntryPoint = "IsWindow")]
private static extern bool IsWindow(int hWnd);

// SendMessage method, using Windows API
[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
);

// SendMessage method, using Windows API
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(
int hWnd, // handle to destination window
int Msg, // message
int wParam, // first message parameter
string lParam // second message parameter
);

笔者查阅了相关网络资源,发现很少有提及使用自定义消息来发送和接收消息的,几乎都是使用了系统消息WM_COPYDATA来实现。在本例中,笔者除了使用系统消息WM_COPYDATA来收发消息外,还将使用自定义消息来实现收发消息。不过,值得注意的是,笔者在测试过程中发现,使用自定义的消息来收发结构体时发生了一些异常,该异常提示说内存不能读,对于该问题,还有待进一步解决,当然,若是哪位前辈或朋友有遇到过该问题并已顺利解决的话,不妨告知,笔者将洗耳恭听。

消息发送类MsgHandler的代码示例如下:

using System;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace CommunicationTest
{
/// <summary>
/// Send message handler class.
/// Call the method "SendMessageToTargetWindow" to send
/// the message what we want.
/// </summary>
class MsgHandler
{
/// <summary>
/// System defined message
/// </summary>
private const int WM_COPYDATA = 0x004A;

/// <summary>
/// User defined message
/// </summary>
private const int WM_DATA_TRANSFER = 0x0437;

// FindWindow method, using Windows API
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);

// IsWindow method, using Windows API
[DllImport("User32.dll", EntryPoint = "IsWindow")]
private static extern bool IsWindow(int hWnd);

// SendMessage method, using Windows API
[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
);

// SendMessage method, using Windows API
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(
int hWnd, // handle to destination window
int Msg, // message
int wParam, // first message parameter
string lParam // second message parameter
);

/// <summary>
/// CopyDataStruct
/// </summary>
private struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}

/// <summary>
/// Send message to target window
/// </summary>
/// <param name="wndName">The window name which we want to found</param>
/// <param name="msg">The message to be sent, string</param>
/// <returns>success or not</returns>
public static bool SendMessageToTargetWindow(string wndName, string msg)
{
Debug.WriteLine(string.Format("SendMessageToTargetWindow: Send message to target window {0}: {1}", wndName, msg));

int iHWnd = FindWindow(null, wndName);
if (iHWnd == 0)
{
string strError = string.Format("SendMessageToTargetWindow: The target window [{0}] was not found!", wndName);
MessageBox.Show(strError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Debug.WriteLine(strError);
return false;
}
else
{
byte[] bytData = null;
bytData = Encoding.Default.GetBytes(msg);

COPYDATASTRUCT cdsBuffer;
cdsBuffer.dwData = (IntPtr)100;
cdsBuffer.cbData = bytData.Length;
cdsBuffer.lpData = Marshal.AllocHGlobal(bytData.Length);
Marshal.Copy(bytData, 0, cdsBuffer.lpData, bytData.Length);

// Use system defined message WM_COPYDATA to send message.
int iReturn = SendMessage(iHWnd, WM_COPYDATA, 0, ref cdsBuffer);
if (iReturn < 0)
{
string strError = string.Format("SendMessageToTargetWindow: Send message to the target window [{0}] failed!", wndName);
MessageBox.Show(strError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Debug.WriteLine(strError);
return false;
}

return true;
}
}

/// <summary>
/// Send message to target window
/// </summary>
/// <param name="wndName">The window name which we want to found</param>
/// <param name="wParam">first parameter, integer</param>
/// <param name="lParam">second parameter, string</param>
/// <returns>success or not</returns>
public static bool SendMessageToTargetWindow(string wndName, int wParam, string lParam)
{
Debug.WriteLine(string.Format("SendMessageToTargetWindow: Send message to target window {0}: wParam:{1}, lParam:{2}", wndName, wParam, lParam));

int iHWnd = FindWindow(null, wndName);
if (iHWnd == 0)
{
string strError = string.Format("SendMessageToTargetWindow: The target window [{0}] was not found!", wndName);
MessageBox.Show(strError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Debug.WriteLine(strError);
return false;
}
else
{
// Use our defined message WM_DATA_TRANSFER to send message.
int iReturn = SendMessage(iHWnd, WM_DATA_TRANSFER, wParam, lParam);
if (iReturn < 0)
{
string strError = string.Format("SendMessageToTargetWindow: Send message to the target window [{0}] failed!", wndName);
MessageBox.Show(strError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Debug.WriteLine(strError);
return false;
}

return true;
}
}
}
}

消息接收重写了DefWndProc方法,其代码示例如下:

/// <summary>
/// Override the DefWndProc function, in order to receive the message through it.
/// </summary>
/// <param name="m">message</param>
protected override void DefWndProc(ref System.Windows.Forms.Message m)
{
switch (m.Msg)
{
// Here, we use WM_COPYDATA message to receive the COPYDATASTRUCT
case WM_COPYDATA:
COPYDATASTRUCT cds = new COPYDATASTRUCT();
cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
byte[] bytData = new byte[cds.cbData];
Marshal.Copy(cds.lpData, bytData, 0, bytData.Length);
this.ProcessIncomingData(bytData);
break;

// Here, we use our defined message WM_DATA_TRANSFER to receive the
// normal data, such as integer, string.
// We had try to use our defined message to receive the COPYDATASTRUCT,
// but it didn't work!! It told us that we try to access the protected
// memory, it usually means that other memory has been broken.
case WM_DATA_TRANSFER:
int iWParam = (int)m.WParam;
string sLParam = m.LParam.ToString();
this.ProcessIncomingData(iWParam, sLParam);
break;

default:
base.DefWndProc(ref m);
break;
}
}

消息的接收与发送最终通过一个WinForm展现出来,其代码实现如下:

using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace CommunicationTest
{
public partial class FrmTest : Form
{
/// <summary>
/// System defined message
/// </summary>
private const int WM_COPYDATA = 0x004A;

/// <summary>
/// User defined message
/// </summary>
private const int WM_DATA_TRANSFER = 0x0437;

/// <summary>
/// CopyDataStruct
/// </summary>
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}

public FrmTest()
{
InitializeComponent();
}

/// <summary>
/// Override the DefWndProc function, in order to receive the message through it.
/// </summary>
/// <param name="m">message</param>
protected override void DefWndProc(ref System.Windows.Forms.Message m)
{
switch (m.Msg)
{
// Here, we use WM_COPYDATA message to receive the COPYDATASTRUCT
case WM_COPYDATA:
COPYDATASTRUCT cds = new COPYDATASTRUCT();
cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
byte[] bytData = new byte[cds.cbData];
Marshal.Copy(cds.lpData, bytData, 0, bytData.Length);
this.ProcessIncomingData(bytData);
break;

// Here, we use our defined message WM_DATA_TRANSFER to receive the
// normal data, such as integer, string.
// We had try to use our defined message to receive the COPYDATASTRUCT,
// but it didn't work!! It told us that we try to access the protected
// memory, it usually means that other memory has been broken.
case WM_DATA_TRANSFER:
int iWParam = (int)m.WParam;
string sLParam = m.LParam.ToString();
this.ProcessIncomingData(iWParam, sLParam);
break;

default:
base.DefWndProc(ref m);
break;
}
}

/// <summary>
/// Process the incoming data
/// </summary>
/// <param name="data">incoming data</param>
private void ProcessIncomingData(byte[] bytesData)
{
string strRevMsg = "Receive message: " + Encoding.Default.GetString(bytesData);

lstReceivedMsg.Items.Add(strRevMsg);
}

/// <summary>
/// Process the incoming data
/// </summary>
/// <param name="iWParam">a integer parameter</param>
/// <param name="sLParam">a string parameter</param>
private void ProcessIncomingData(int iWParam, string sLParam)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append("wParam: ");
strBuilder.Append(iWParam.ToString());
strBuilder.Append(", lParam: ");
strBuilder.Append(sLParam);

lstReceivedMsg.Items.Add(strBuilder.ToString());
}

private void FrmTest_Load(object sender, EventArgs e)
{
this.Text = "First Test Form";
this.txtCurrentWndName.Text = "First Test Form";
this.txtTargetWndName.Text = "Second Test Form";
}

private void txtCurrentWndName_TextChanged(object sender, EventArgs e)
{
this.Text = txtCurrentWndName.Text;
}

/// <summary>
/// Send message to the target window with system defined message WM_COPYDATA
/// </summary>
private void btnSend1_Click(object sender, EventArgs e)
{
string strWndName = this.txtTargetWndName.Text;
// Check the target window name is null/empty or not
if (string.IsNullOrEmpty(strWndName))
{
MessageBox.Show("The target window name must not be null or empty!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}

string strMsg = this.txtSendingMsg.Text;
// Check the sending message is null/empty or not
if (string.IsNullOrEmpty(strMsg))
{
MessageBox.Show("The sending message must not be null or empty!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}

// Send message to the target window
bool bReturn = MsgHandler.SendMessageToTargetWindow(strWndName, strMsg);
}

/// <summary>
/// Send message to the target window with user defined message WM_DATA_TRANSFER
/// </summary>
private void btnSend2_Click(object sender, EventArgs e)
{
string strWndName = this.txtTargetWndName.Text;
// Check the target window name is null/empty or not
if (string.IsNullOrEmpty(strWndName))
{
MessageBox.Show("The target window name must not be null or empty!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}

string strWParam = this.txtWParam.Text;
string strLParam = this.txtLParam.Text;
// Check the sending message is null/empty or not
if (string.IsNullOrEmpty(strWParam) || string.IsNullOrEmpty(strLParam))
{
MessageBox.Show("The sending message must not be null or empty!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}

int iWParam = 0;
// Convert string to integer
try
{
iWParam = Int32.Parse(strWParam);
}
catch (Exception ex)
{
MessageBox.Show("Convert string to integer exception: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

// Send message to the target window
bool bReturn = MsgHandler.SendMessageToTargetWindow(strWndName, iWParam, strLParam);
}
}
}

通过上述的C#部分的代码,已经可以实现两个C#窗体间的通信,其界面截图如下图所示:

那么,在C++中又是如何实现的呢?这个其实也是很简单的。要实现消息的收发,同理也要重写WindowProc以便于接收消息,而通过调用方法亦可实现消息的发送。
    对于消息接收,如果是系统消息,可以通过OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)事件完成;如果是自定义消息,可以通过重写WindowProc完成。代码示例如下:

BOOL CTestDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值

DWORD dwSize = pCopyDataStruct->cbData;

CString szData;// = (LPCTSTR)(pCopyDataStruct->lpData);
TCHAR* ptchar = new TCHAR[dwSize+1];

memcpy( ptchar, pCopyDataStruct->lpData, dwSize );
ptchar[dwSize] = TEXT('/0');
szData = ptchar;
// TODO: Add some code here to handler the message

delete[] ptchar;

return CDialog::OnCopyData(pWnd, pCopyDataStruct);
}

LRESULT CTestDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: 在此添加专用代码和/或调用基类
COPYDATASTRUCT szCpyData;

switch ( message )
{
case WM_DATA_TRANSFER:
szCpyData = *((PCOPYDATASTRUCT)lParam);
// TODO: Add some code here to handler the message
break;

default:
break;
}

return CDialog::WindowProc(message, wParam, lParam);
}

    对于消息发送,只需要调用形如SendMessage(m_hwndMsg, WM_DATA_TRANSFER, wParam, lParam)方法即可实现,lParam参数可以是PCOPYDATASTRUCT等。

通过上面的介绍,相信已经可以轻松实现两个进程间(含窗体)的通信的,使用这样的方法,既简单又能够满足大部分的应用需求,不失为一种简便的方法。

c# 进程间的通信实现之一简单字符串收发的更多相关文章

  1. c 进程间的通信

    在上篇讲解了如何创建和调用进程 c 进程和系统调用 这篇文章就专门讲讲进程通信的问题 先来看一段下边的代码,这段代码的作用是根据关键字调用一个Python程序来检索RSS源,然后打开那个URL #in ...

  2. Android进程间的通信之AIDL

    Android服务被设计用来执行很多操作,比如说,可以执行运行时间长的耗时操作,比较耗时的网络操作,甚至是在一个单独进程中的永不会结束的操作.实现这些操作之一是通过Android接口定义语言(AIDL ...

  3. Android进程间的通信之Messenger

    Android进程间的通信方式可以通过以下两种方式完成: Android接口定义语言(AIDL) 使用Messenger绑定服务 本文我们将学习使用Messenger绑定服务的方式进行进程间的通信. ...

  4. Linux进程间的通信

    一.管道 管道是Linux支持的最初Unix IPC形式之一,具有以下特点: A. 管道是半双工的,数据只能向一个方向流动: B. 需要双工通信时,需要建立起两个管道: C. 只能用于父子进程或者兄弟 ...

  5. [Socket]Socket进程间的通信

    转自:http://blog.csdn.net/giantpoplar/article/details/47657303 前面说到的进程间的通信,所通信的进程都是在同一台计算机上的,而使用socket ...

  6. 从AIDL开始谈Android进程间Binder通信机制

    转自: http://tech.cnnetsec.com/585.html 本文首先概述了Android的进程间通信的Binder机制,然后结合一个AIDL的例子,对Binder机制进行了解析. 概述 ...

  7. c++ 网络编程(三) LINUX/windows 进程间的通信原理与实现代码 基于多进程的服务端实现

    原文作者:aircraft 原文链接:https://www.cnblogs.com/DOMLX/p/9613027.html 锲子:进程与线程是什么,他们的区别在哪里: 1 进程概念 进程是程序的一 ...

  8. Android进程间的通信

    1.概述:由于android系统中应用程序之间不能共享内存.因此,在不同应用程序之间交互数据(跨进程通讯)就稍微麻烦一些.在android SDK中提供了4种用于跨进程通讯的方式.这4种方式正好对应于 ...

  9. Nginx学习——Nginx进程间的通信

    nginx进程间的通信 进程间消息传递 共享内存 共享内存还是Linux下提供的最主要的进程间通信方式,它通过mmap和shmget系统调用在内存中创建了一块连续的线性地址空间,而通过munmap或者 ...

随机推荐

  1. 第三个Sprint冲刺第十天

    讨论地点:宿舍 讨论成员:邵家文.李新.朱浩龙.陈俊金 讨论问题:做最后的工作

  2. formValidator 表单验证

    作为一名程序员,在解决工作中遇到问题之后,做一些总结是有必要的,既方便总结温习相关知识点,也为广大的程序员提供了一些工作经历,给予同行一面明鉴. 首先,众所周知的,我们需要引用js类库: eg:< ...

  3. shell单引号中输出参数值

    因为在shell的单引号中,所有的特殊字符和变量都会变成文本,那么如果需要在字符串中输出变量值怎么办呢? 这里记录以下两种方法: 使用双引号 shell> X='parameter' shell ...

  4. ionic cordova 热更新的一些问题

    因为项目需要用到更新这一块的东西,所以就查了下cordova 的热更新,然后遇到了 一些问题,记录下来备忘. 项目用的是ionic 下载cordova的内容就直接跳过了. 首先是下载cordova的插 ...

  5. SVN更新报错

    将服务器SVN文件更新到本地是出现下图错误 报错中已经提示可以通过clean up来清理,若直接执行release lock,则不会解决问题. 原因:本地的项目中存在过期的工作副本 解决办法:选择该文 ...

  6. Spark RDD API详解(一) Map和Reduce

    RDD是什么? RDD是Spark中的抽象数据结构类型,任何数据在Spark中都被表示为RDD.从编程的角度来看,RDD可以简单看成是一个数组.和普通数组的区别是,RDD中的数据是分区存储的,这样不同 ...

  7. Eclipse中的Link with Editor功能是如何实现

    Eclipse中的Link with Editor功能是如何实现 - kaukiyou的专栏 - 博客频道 - CSDN.NEThttp://blog.csdn.net/kaukiyou/articl ...

  8. unity行为树制作AI简单例子(1)

    用行为树来制作AI是非常方便的,今天就给大家简单介绍一下行为树的强大之处. 所用插件 Behavior Designer v1.421 最开始 我使用过Rain插件,不过用过Behavior Desi ...

  9. [UI]抽屉菜单DrawerLayout分析(一)

    本文转载于:http://www.cnblogs.com/avenwu/archive/2014/04/16/3669367.html 侧拉菜单作为常见的导航交互控件,最开始在没有没有android官 ...

  10. js 浏览器兼容的一些方法

    使用js是一件令人很抓狂的事情,很多的浏览器兼容,一大推的代码,谁的脑袋能记住那么多的东西,只有平时多积累,所谓熟能生巧嘛..这里列出一些常用的兼容代码,一点点积累哈~~~     一.以跨浏览器的方 ...