我今天遇到了同样的问题。至少,我用这种方式解决了这个问题:
使用Newtonsoft.Json.dll,序列化和反序列化对象,并通过WM_COPYDATA消息传递字符串。
在主机应用程序中:
呼叫子应用程序:
private void RunChild()
{
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
string childPath = Path.Combine(appPath, "ChildApp.exe");
Process.Start(childPath, this.Handle.ToString());
}
接收消息:
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case WM_COPYDATA:
COPYDATASTRUCT copyData = new COPYDATASTRUCT();
Type type = copyData.GetType();
copyData = (COPYDATASTRUCT)m.GetLParam(type);
string data = copyData.lpData;
RestorePerson(data);
break;
}
}
反序列化对象:
private void RestorePerson(string data)
{
var p = JsonConvert.DeserializeObject<Person>(data);
txtName.Text = p.Name;
txtAge.Text = p.Age.ToString();
}
在儿童应用程序中:
获取主机句柄:
public ChildForm(string[] args)
{
InitializeComponent();
if (args.Length != 0)
this.hostHandle = (IntPtr)int.Parse(args[0]);
}
发送序列化字符串:
private void btnSubmit_Click(object sender, EventArgs e)
{
this.person.Name = txtName.Text;
this.person.Age = int.Parse(txtAge.Text);
if (this.hostHandle != IntPtr.Zero)
{
string data = JsonConvert.SerializeObject(this.person);
COPYDATASTRUCT cds = new COPYDATASTRUCT();
cds.dwData = (IntPtr)901;
cds.cbData = data.Length + 1;
cds.lpData = data;
SendMessage(this.hostHandle, WM_COPYDATA, 0, ref cds);
}
}
//class Person can used by HostApp by add refrence.
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
它工作正常!试试看?