WM_COPYDATA Win32 -> C#

M

Mike Tinnes

Can someone explain why this doesn't work? I'm trying to send a string
from a Win32 dll to a C# winform. The dwData and cbData members are
good, but lpData is always garbage on the .NET side.


Win32
--------------------
COPYDATASTRUCT cds;
char szText[255];
lstrcpy(szText, "testing");
cds.dwData = 0;
cds.lpData = (LPSTR)szText;
cds.cbData = sizeof(szText);

SendMessage((HWND)g_hClient, WM_COPYDATA, (WPARAM)g_hWnd,
(LPARAM)&cds);


C#
---------------------
protected override void WndProc(ref Message message)
{
switch(message.Msg)
{
case (int)WinAPI.WmDefs.WM_COPYDATA:
WinAPI.COPYDATASTRUCT st =
(WinAPI.COPYDATASTRUCT)Marshal.PtrToStructure(message.LParam,
typeof(WinAPI.COPYDATASTRUCT));
string str = Marshal.PtrToStringUni(st.lpData, st.cbData);
MessageBox.Show(str);
break;
default:
base.WndProc(ref message);
break;
}
}
 
B

Brian Martel

This sample code I got from somewhere is working.

[StructLayout(LayoutKind.Sequential)]
struct COPYDATASTRUCT
{
public int dwData;
public int cbData;
public int lpData;
}

private const int WM_COPYDATA = 0x4A;

// Window proc that receives the WM_ messages for the associated window
handle
protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case WM_COPYDATA:
COPYDATASTRUCT CD =
(COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
byte[] B = new byte[CD.cbData];
IntPtr lpData = new IntPtr(CD.lpData);
Marshal.Copy(lpData, B, 0, CD.cbData);
string strData = Encoding.Default.GetString(B);
form.OpenGamls(new string[] {strData});
break;

default:
// let the base class deal with it
base.WndProc(ref m);
break;
}
}
 

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