Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Inter-Process Communication with C#

0.00/5 (No votes)
11 Jul 2007 1  
This app shows how to send and receive messages between apps using WM_COPYDATA.

Introduction

This app shows how to send and receive messages between two apps using WM_COPYDATA.

There are two samples. One is testmessage app and one is testMessage2 app. The testmessage will check and open app 2 if it is not running and if so, will start another instance with a different window header.

  • The 'Send' button will send the text from the textbox to the testMessage2 app.
  • The received data will show up in the textbox.

Using the Code

The exchange of data is performed by finding the other application (using FindWindow) and sending a WM_COPYDATA message to that window:

 public static bool SendArgs(IntPtr targetHWnd, string args)
        {
            Win32.CopyDataStruct cds = new Win32.CopyDataStruct();
            try
            {
                cds.cbData = (args.Length + 1) * 2;
                cds.lpData = Win32.LocalAlloc(0x40, cds.cbData);
                Marshal.Copy(args.ToCharArray(), 0, cds.lpData, args.Length);
                cds.dwData = (IntPtr)1;
                Win32.SendMessage(targetHWnd, Win32.WM_COPYDATA, IntPtr.Zero, ref cds);
            }
            finally
            {
                cds.Dispose();
            }

            return true;
        } 
protected override void WndProc(ref Message m){
            switch(m.Msg){
                case Win32.WM_COPYDATA:
                    Win32.CopyDataStruct st =
            	  (Win32.CopyDataStruct)Marshal.PtrToStructure(m.LParam,             
		  typeof(Win32.CopyDataStruct));
                    string strData = Marshal.PtrToStringUni(st.lpData);
                    txtmessagereceive.Text = strData;
                    break;

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

History

  • 12th July, 2007: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here