Connecting Tech Pros Worldwide Forums | Help | Site Map

C# SendMessage with WM_COPYDATA

Newbie
 
Join Date: Oct 2008
Posts: 19
#1: Oct 9 '08
I have two C# Applications. The first application has to send 2 strings to the other application. The first string is just a simple string "abc", while the 2nd string contains a path (Application.StartupPath). This is the code I use to send the data:

Expand|Select|Wrap|Line Numbers
  1.         //Used for WM_COPYDATA for string messages
  2.         public struct COPYDATASTRUCT
  3.         {
  4.             public IntPtr dwData;
  5.             public int cbData;
  6.             [MarshalAs(UnmanagedType.LPStr)]
  7.             public string jobName;
  8.             [MarshalAs(UnmanagedType.LPStr)]
  9.             public string path;
  10.         }
  11.  
  12.         public int sendWindowsStringMessage(int hWnd, int wParam, string msg)
  13.         {
  14.             int result = 0;
  15.  
  16.             if (hWnd > 0)
  17.             {
  18.                 byte[] sarr = System.Text.Encoding.Default.GetBytes(msg);
  19.                 int len = sarr.Length;
  20.                 COPYDATASTRUCT cds = new COPYDATASTRUCT();
  21.                 cds.dwData = (IntPtr)100;
  22.                 cds.jobName = msg; //first string
  23.                 cds.path = Application.StartupPath; //path string
  24.                 cds.cbData = len + 1;
  25.                 result = SendMessage(hWnd, WM_COPYDATA, wParam, ref cds);
  26.             }
  27.  
  28.             return result;
  29.         }
And this is how I listen for it:

Expand|Select|Wrap|Line Numbers
  1.         //Receives Windows Messages
  2.         protected override void WndProc(ref Message message)
  3.         {
  4.             if (message.Msg == WM_COPYDATA)
  5.             {
  6.                 COPYDATASTRUCT mystr = new COPYDATASTRUCT();
  7.                 Type mytype = mystr.GetType();
  8.                 mystr = (COPYDATASTRUCT)message.GetLParam(mytype);
  9.  
  10.                 //see what path is being passed.
  11.                 MessageBox.Show(mystr.path);
  12.  
  13.                 //Process
  14.                 Process(mystr.jobName);
  15.  
  16.  
  17.             }
  18.             //be sure to pass along all messages to the base also
  19.             base.WndProc(ref message);
  20.         }
The first string (jobName) is received fine, but the second string (path) comes up as a bunch of garbage characters. The path on the sending side is sent as "C:\\Path\\Dir", on the receiving side i get "¸`dã"

Any idea why path strings aren't being sent correctly?

Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,161
#2: Oct 9 '08

re: C# SendMessage with WM_COPYDATA


instead of using string Path (etc) try doing it with a StringBuilder ?
I have seen people have luck using a stringbuilder through marshalling vs strings
Reply