hi, i'm trying to let 2 application communicate with each other using windows message. however, i've been getting AccessViolationException (attempted to read or write protected memory) during allocating memory and marshaling of data.
Can someone explain to me what's wrong or suggest a better way? Thanks.
EDIT: using WM_COPYDATA as suggested, but now i've got another problem - the other application isn't receiving the WM_COPYDATA message. what's wrong?
code for sending msg:
public const int WM_COPYDATA = 0x004A;
public struct COPYDATASTRUCT
{
public int dwData;
public int cbData;
public DATA lpData;
}
public struct DATA
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=50)]
public char[] msg1;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=50)]
public char[] msg2;
}
[DllImport("User32.dll")]
public static extern int SendMessage(int hWnd, int Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
private void button1_Click(object sender, EventArgs e)
{
// data, with null terminated strings
COPYDATASTRUCT cds = new COPYDATASTRUCT();
cds.lpData.msg1 = textBox2.Text.PadRight(50, '\0').ToCharArray();
cds.lpData.msg2 = textBox3.Text.PadRight(50, '\0').ToCharArray();
cds.cbData = Marshal.SizeOf(cds.lpData);
int result = SendMessage(hwnd, WM_COPYDATA, System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle, ref cds); // winAPI
}
code for receiving msg (in the other app):
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_COPYDATA)
{
// doesn't get into this part
COPYDATASTRUCT cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
....
}
base.WndProc(ref m);
}