利用WM_COPYDATA可以轻松实现两个进程间的通信,但是一般都是传string数据,今天看到优快云上有人问如何传Struct。下面是我的解决方法。
[StructLayout(LayoutKind.Sequential)]
publicstructCOPYDATASTRUCT


{
publicintdwData;
publicintcbData;
publicintlpData;
}
[DllImport("user32",EntryPoint="SendMessageA")]
publicstaticexternintSendMessage(intHwnd,intwMsg,intwParam,refCOPYDATASTRUCTlParam);
constintWM_COPYDATA=0x004A;

//定义要传递的Struct
[StructLayout(LayoutKind.Sequential)]
structWholeInfo


{
//SizeConst指定字符串很重要,后面要用到
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=10)]
publicstringcPath;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=10)]
publicstringlPath;
publicboolstatus;
}


//发送方代码

WholeInfoh=newWholeInfo();
h.lPath="lPath";
h.cPath="cPath";
h.status=true;
intsize=Marshal.SizeOf(typeof(WholeInfo));
byte[]Bytes=newbyte[size];
//根据定义的尺寸分配内存块
GCHandleGC=GCHandle.Alloc(Bytes,GCHandleType.Pinned);
IntPtrptr1=GC.AddrOfPinnedObject();
//获得Struct对应的IntPtr
Marshal.StructureToPtr(h,ptr1,false);
SendData.lpData=ptr1.ToInt32();
SendData.cbData=size;

intintHWnd=FindWindow(null,@"接收方");
if(intHWnd>0)


{
SendMessage(intHWnd,WM_COPYDATA,0,ref(SendData));
}

//接收方代码

//处理消息
protectedoverridevoidDefWndProc(refSystem.Windows.Forms.Messagem)


{
switch(m.Msg)


{
caseWM_COPYDATA:
COPYDATASTRUCTRecvData=(COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
WholeInfoh=(WholeInfo)Marshal.PtrToStructure((IntPtr)RecvData.lpData,typeof(WholeInfo));
this.textBox1.Text=h.cPath;

break;
default:
base.DefWndProc(refm);
break;

}

}












































































关键的代码就是
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
这样C#才能分配正确的内存位置,但是要记住一个汉字占2位