接上篇:
高级方案与简易方案的区别主要在于:前者可以定义需要传递的struct。
公用结构:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace Common
{
//发送共享消息的结构
[StructLayout(LayoutKind.Sequential)]
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public int lpData;
}
//定义要传递的Struct
[StructLayout(LayoutKind.Sequential)]
public struct WholeInfo
{
//SizeConst指定字符串长度很重要,后面要用到
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10000)]
public string str1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10000)]
public string str2;
public bool status;
}
}
发送方:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace ProjectA
{
public partial class SenderForm : Form
{
const int WM_COPYDATA = 0x004A;
//发送消息的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 Common.COPYDATASTRUCT lParam // second message parameter
);
//通过窗体标题找出窗体的Handle
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
public SenderForm()
{
InitializeComponent();
}
private void btnSendMsg_Click(object sender, EventArgs e)
{
Common.WholeInfo h = new Common.WholeInfo();
h.str1 = txtMsg.Text;
h.str2 = txtMsg2.Text ;
h.status = true;
int size = Marshal.SizeOf(typeof(Common.WholeInfo));
byte[] Bytes = new byte[size];
//根据定义的尺寸分配内存块
GCHandle GC = GCHandle.Alloc(Bytes, GCHandleType.Pinned);
IntPtr ptr1 = GC.AddrOfPinnedObject();
//获得Struct对应的IntPtr
Marshal.StructureToPtr(h, ptr1, false);
Common.COPYDATASTRUCT SendData = new Common.COPYDATASTRUCT();
SendData.lpData = ptr1.ToInt32();
SendData.cbData = size;
//找出接收方窗体的FormHandle
int intHWnd = FindWindow(null, @"接收方");
if (intHWnd > 0)
{
//发送消息
SendMessage(intHWnd, WM_COPYDATA, 0, ref (SendData));
}
}
}
}
接收方:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace ProjectB
{
public partial class ReceiverForm : Form
{
const int WM_COPYDATA = 0x004A;
public ReceiverForm()
{
InitializeComponent();
}
protected override void DefWndProc(ref System.Windows.Forms.Message m)
{
switch (m.Msg)
{
case WM_COPYDATA:
//取出结构
Common.COPYDATASTRUCT RecvData = (Common.COPYDATASTRUCT)m.GetLParam(typeof(Common.COPYDATASTRUCT));
//转换取出定义的传递结构
Common.WholeInfo h = (Common.WholeInfo)Marshal.PtrToStructure((IntPtr) RecvData.lpData, typeof(Common.WholeInfo));
this.txtMsg.Text = h.str1;
this.txtMsg2.Text = h.str2;
break;
default:
base.DefWndProc(ref m);
break;
}
}
}
}