C# SendMessage with WM_COPYDATA

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • xMetalDetectorx
    New Member
    • Oct 2008
    • 44

    C# SendMessage with WM_COPYDATA

    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.St artupPath). This is the code I use to send the data:

    Code:
            //Used for WM_COPYDATA for string messages
            public struct COPYDATASTRUCT
            {
                public IntPtr dwData;
                public int cbData;
                [MarshalAs(UnmanagedType.LPStr)]
                public string jobName;
                [MarshalAs(UnmanagedType.LPStr)]
                public string path;
            }
    
            public int sendWindowsStringMessage(int hWnd, int wParam, string msg)
            {
                int result = 0;
    
                if (hWnd > 0)
                {
                    byte[] sarr = System.Text.Encoding.Default.GetBytes(msg);
                    int len = sarr.Length;
                    COPYDATASTRUCT cds = new COPYDATASTRUCT();
                    cds.dwData = (IntPtr)100;
                    cds.jobName = msg; //first string
                    cds.path = Application.StartupPath; //path string
                    cds.cbData = len + 1;
                    result = SendMessage(hWnd, WM_COPYDATA, wParam, ref cds);
                }
    
                return result;
            }
    And this is how I listen for it:

    Code:
            //Receives Windows Messages
            protected override void WndProc(ref Message message)
            {
                if (message.Msg == WM_COPYDATA)
                {
                    COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                    Type mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)message.GetLParam(mytype);
    
                    //see what path is being passed.
                    MessageBox.Show(mystr.path);
    
                    //Process
                    Process(mystr.jobName);
    
                    
                }
                //be sure to pass along all messages to the base also
                base.WndProc(ref message);
            }
    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
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    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

    Comment

    Working...