Marshalling strings: SendMessage & WndProc

J

James Burrow

Hi,

I am trying to write a 2 .net programs that can communicate via
windows messages. I have achieved this but only just passing ints.
When i try and pass a string, i get junk out. I guess this something
to do with the processes the pointers relate too. I have tried hunting
around for answer but i am unsure where to look, google has drawn a
blank. Any help to solve this problem or to point me in the direction
of some articles.

Would be great.

Thanks in advance.

James Burrow

Program 1
[DllImport("user32.dll", CharSet=CharSet.Auto)]
static extern int SendMessage(IntPtr hwnd, int wMsg, int
wParam,[MarshalAs(UnmanagedType.LPStr)] ref string lParam);

[DllImport("user32.dll",EntryPoint="FindWindow",CharSet=CharSet.Auto)]
public static extern int FindWindow(string _WindowClassName, string
_WindowName);

private void button2_Click(object sender, System.EventArgs e)
{
int HWND = FindWindow(null,"Recieve Message");
Console.WriteLine(HWND);

if(HWND>0)
{
string sSendData = "JAMESTEST";
SendMessage(new IntPtr(HWND), WM_CURRENTSONG, sSendData.Length, ref
sSendData);
}
}


Program 2
protected override void WndProc(ref Message m)
{
if(m.Msg==WM_CURRENTSONG)
{
int iLength = m.WParam.ToInt32();
string sTheString = Marshal.PtrToStringAuto(m.LParam);
Console.WriteLine("Length:{0} String:{1}",iLength,sTheString);
}

base.WndProc (ref m);
}
 
N

Nicholas Paldino [.NET/C# MVP]

James,

You are right in your assumption. When you call SendMessage and pass a
value which is a pointer to another process, the address means something
completely different to the other process, as it is a different memory space
altogether.

So, you can use WM_COPYDATA, as another poster suggested, or you can use
some other techniques, such as remoting, to pass data between processes.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top