文章目录
- 一、在两个进程之间建立一个共同区域
- 二、利用API函数去找到进程窗口的句柄,然后用API去控制这个窗口
- 三、方式选择
- 四、示例【使用Process类和API实现两个进程之间的数据传输】
- 程序结构如下:
- WindowsFormsApp1的代码
- WindowsFormsApp2的代码
- 操作步骤:
- 运行结果:
目前,网上关于C#进程间通信的方法有很多种,但是总结起来它们不外乎从以下两个方面进行考虑:
一、在两个进程之间建立一个共同区域
其中一个进程改变这个区域的内容,而另一个进程则去读取它,反之亦然。
比如,可以让两个进程共享同一块内存,通过改变和读取内存中的内容进行通信;或者,创建一个文件,两个进程同时占用,甚至可以利用注册表或者剪贴板充当这个“共同区域”。
【疑问】???
如何两个进程共享一块内存?
如何利用注册表或者剪贴板充当这个“共同区域”?
二、利用API函数去找到进程窗口的句柄,然后用API去控制这个窗口
例如,导入“User32.dll”中的FindWindow、FindWindowEx函数查找窗口,并获取窗口句柄。也可直接利用C#中的Process类来启动程序,并获取这个进程的主窗口的句柄,等等。
【疑问】???
如何通过“User32.dll”中的FindWindow、FindWindowEx函数查找窗口,并获取窗口句柄?
三、方式选择
在编程时,我们往往需要选择一种既方便编写,效率又高的程序。
第一种类型相对比较复杂,而且效率不高。
相比来讲,第二种类型在不降低程序运行效率的情况下编写更简单。
四、示例【使用Process类和API实现两个进程之间的数据传输】
新建一个程序,其中有两个项目,分别为WindowsFormsApp1和WindowsFormsApp2,
生成的程序分别为:Form1和Form2


程序结构如下:


WindowsFormsApp1的代码
WindowsFormsApp1中Form1窗体如下:

Form1代码如下:
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
this.label1.Text = Convert.ToString(e.KeyValue);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
WindowsFormsApp2的代码
WindowsFormsApp1中Form1窗体如下:

Form1的代码:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage1(IntPtr wnd, int msg, IntPtr wP, IntPtr lP);
ProcessStartInfo psInfo = new ProcessStartInfo(@"..\..\..\WindowsFormsApp1\bin\Debug\Form1.exe");
Process pro = new Process();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pro.StartInfo = psInfo;
}
private void button1_Click(object sender, EventArgs e)
{
pro.Start();
}
private void button2_Click(object sender, EventArgs e)
{
pro.Kill();
}
private void button3_Click(object sender, EventArgs e)
{
IntPtr hWnd = pro.MainWindowHandle;
int data = Convert.ToInt32(this.textBox1.Text);
SendMessage1(hWnd, 0x0100, (IntPtr)data, (IntPtr)0);
}
}
}
操作步骤:
- 打开Form2.exe
- 点击打开程序,Form1.exe被打开
- 点击“发送消息”,Form1.exe接收到Form2.exe传输过来的值,并显示。
运行结果:
