public static class WindowsApiHelper
{
/// <summary>
/// 进程通信类
/// </summary>
/// <param name="hWnd"></param>
/// <param name="Msg"></param>
/// <param name="wParam"></param>
/// <param name="Param"></param>
/// <returns></returns>
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref COPYDATASTRUCT Param);
// 导出FindWindow函数,用于找到目标窗口所在进程
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
public const int WM_COPYDATA = 0x004A; // 固定数值,不可更改
public struct COPYDATASTRUCT
{
public IntPtr dwData; // 任意值
public int cbData; // 指定lpData内存区域的字节数
[MarshalAs(UnmanagedType.LPStr)]
public string lpData; // 发送给目标窗口所在进程的数据
}
public static void SendMessagetToOherWindow(string exeName,string message)
{
//Process[] procs = Process.GetProcesses();
Process[] processes = Process.GetProcessesByName(exeName);
foreach (Process p in processes)
{
// 获取目标进程句柄
IntPtr hWnd = p.MainWindowHandle;
// 封装消息
byte[] sarr = System.Text.Encoding.Default.GetBytes(message);
int len = sarr.Length;
COPYDATASTRUCT cds2;
cds2.dwData = (IntPtr)0;
cds2.cbData = len + 1;
cds2.lpData = message;
// 发送消息
SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, ref cds2);
}
}
}
创建类WindowsApiHelper,然后在wpf的mainwindow中设置钩子,捕获另一进程发过来的消息
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
if (hwndSource != null)
{
IntPtr handle = hwndSource.Handle;
hwndSource.AddHook(new HwndSourceHook(WndProc));
}
}
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_COPYDATA)
{
COPYDATASTRUCT cds = (COPYDATASTRUCT)Marshal.PtrToStructure(lParam,
typeof(COPYDATASTRUCT)); // 接收封装的消息
string rece = cds.lpData; // 获取消息内容
// 自定义行为
if(rece =="123"){ }
}
return hwnd;
}
然后直接调用SendMessagetToOherWindow即可向另一进程发送消息,两个进程都设置钩子,即可实现进程互相通信,互相捕获消息