我需要将一个类的对象从一个程序传递到另一个程序。
这是我需要通过的课程;
[StructLayout( LayoutKind.Sequential, CharSet = CharSet.Ansi )]
public class MessageContainer
{
public bool DescFirst { get; set; }
[MarshalAs( UnmanagedType.ByValTStr, SizeConst = 200 )]
public string Data;
public decimal PriceMin { get; set; }
public int Hidden { get; set; }
public MessageContainer()
{
DescFirst = true;
}
}
复制数据结构类;
public struct CopyDataStruct : IDisposable
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
public void Dispose()
{
if (this.lpData != IntPtr.Zero)
{
LocalFree(this.lpData);
this.lpData = IntPtr.Zero;
}
}
}
我如何发送对象;
{
int hwnd = -1;
IntPtr handle = IntPtr.Zero;
foreach (Process proc in Process.GetProcesses())
{
if (proc.MainWindowTitle.StartsWith("MyApp"))
{
handle = proc.MainWindowHandle;
}
}
if (handle != IntPtr.Zero)
{
Win32.CopyDataStruct cds = new Win32.CopyDataStruct();
MessageContainer cs = new MessageContainer();
cs.Data = "Test123";
cds.DescFirst = true;
cds.lpData = Marshal.AllocHGlobal(Marshal.SizeOf(cs));
cs.PriceMin = "1.25";
cs.Hidden = 0;
try
{
Marshal.StructureToPtr(cs, cds.lpData, false);
Win32.SendMessage(handle, Win32.WM_COPYDATA, IntPtr.Zero, ref cds);
}
finally
{
Marshal.FreeHGlobal(cds.lpData);
}
}
else
MessageBox.Show("Not send");
}
在另一个应用程序上;
protected override void WndProc(ref Message m)
{
switch ( m.Msg )
{
case Win32.WM_COPYDATA:
Win32.CopyDataStruct cds = (Win32.CopyDataStruct)m.GetLParam(typeof(Win32.CopyDataStruct));
// If the size matches
if ( cds.cbData == Marshal.SizeOf(typeof(MessageContainer)) )
{
MessageContainer msg = (MessageContainer)Marshal.PtrToStructure(cds.lpData, typeof(MessageContainer));
if ( msg != null )
{
TextBox1.text = msg.Data;
}
}
break;
default:
// let the base class deal with it
base.WndProc(ref m);
break;
}
}
我在目标应用程序上获得了除“字符串”数据类型(“Test123”)之外的所有数据。将“数据”留空。
没有错误,两个应用程序都可以工作。对象被传输,但在字符串变量上没有数据。
请帮助我