Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

.NET Interprocess Communication

4.89/5 (57 votes)
14 Dec 2009CPOL6 min read 1   5.1K  
An easy-to-use, zero configuration solution to .NET communication across application boundaries. A simple library to use as an alternative to .NET Remoting based on low-level Windows Messaging.
Sample image

Introduction

This article demonstrates a quick and easy-to-use implementation for cross-AppDomain communication in .NET by leveraging Windows native messaging. The XDMessaging library is based on code developed to aid rapid development for a recent Vista project that required a lot of cross-AppDomain communication in a locked-down environment. It proved to be extremely useful in a number of scenarios where .NET Remoting would have been impractical, if not impossible, and actually solved more problems than I could have imagined due to its simplicity. The library is intended to send messages between multiple applications in a same-box scenario. For example, a task-tray application might want to communicate with or monitor a separate desktop application. The library does not implement cross-domain communication across a network, for which case .NET Remoting is sufficient.

Update: XDMessaging 2.0 is now available here, and introduces support for Windows services and console applications.

Background

So, why not use .NET Remoting? Well, in the past I've personally found this extremely tedious to set up and configure. The other issue is the lack of helpful error reporting when things go wrong, invariably with permissions. Don't get me wrong, I'm not opposed to .NET Remoting. It has a lot more functionality than my own implementation, and of course is not limited to communication on a single box. However, for same-box communications, it doesn't need to be that complex. So, why not leverage Windows Messaging? After all, this is the mechanism that unmanaged applications use for exactly this purpose. Well now, there's an idea…

If you've never heard of them, Windows messages are low-level communications used by the Windows operating system to broadcast information regarding user-input, system changes and other events that applications running on the system can react to. For instance, application repaints are triggered by the WM_PAINT message. As well as system messages, unmanaged applications may also define custom Windows messages and use them to communicate with other windows. These usually take the form of WM_USER messages. If you have Spy++ installed (Visual Studio Tools), you can monitor all of the messages that a window receives in real-time.

The XDMessaging Library

The XDMessaging library provides an easy-to-use, zero-configuration solution to same-box cross-AppDomain communications. It provides a simple API for sending and receiving targeted string messages across application boundaries. The library allows the use of user-defined pseudo 'channels' through which messages may be sent and received. Any application can send a message to any channel, but it must register as a listener with the channel in order to receive. In this way, developers can quickly and programmatically devise how best their applications can communicate with each other and work in harmony.

Example: Sending a Message

C#
// Send shutdown message a channel named commands
XDBroadcast.SendToChannel("commands", "shutdown");

Example: Listening on a Channel

C#
// Create our listener instance
XDListener listener = new XDListener();

// Register channels to listen on
listener.RegisterChannel("events");
listener.RegisterChannel("status");
listener.RegisterChannel("commands");

// Stop listening on a specific channel
listener.UnRegisterChannel("status");

Example: Handling the Messages

C#
// Attach an event handler to our instance
listener.MessageReceived+=XDMessageHandler(this.listener_MessageReceived);

// process the message
private void listener_MessageReceived(object sender, XDMessageEventArgs e)
{
    // e.DataGram.Message is the message
    // e.DataGram.Channel is the channel name
    switch(e.DataGram.Message)
    {
        case "shutdown":
            this.Close();
            break;
    }
}

The Messenger Demo

To see the demo, you will need to launch multiple instances of the Messenger.exe application. The demo application serves no practical purpose other than to demonstrate the use of the XDMessaging library. It shows how messages may be passed to multiple instances of a desktop application across application boundaries. The application uses two arbitrary channels, named Status and UserMessage. Window events such as onClosing and onLoad are broadcast as messages on the Status channel (displayed in green) and user messages are broadcast on the UserMessage channel (displayed in blue). By checking or unchecking the options, you may toggle which channel messages the window will listen for.

How It Works

The library makes use of a Windows system message of the type WM_COPYDATA. This system message allows data to be passed between multiple applications by carrying a pointer to the data we wish to copy, in this case a string. This is sent to other windows using the SendMessage Win32 API with PInvoke.

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

[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int SendMessage(IntPtr hwnd, int wMsg, 
    int wParam, ref COPYDATASTRUCT lParam);

The COPYDATASTRUCT struct contains information regarding the message data that we want to transfer to another application. This is referenced by the members lpData and dwData. lpData is a pointer to the string data that is stored in memory. dwData is the size of the transfer data. The cdData member is not used in our case. In order to pass the data, we must first allocate the message string to an address in memory and get a pointer to this data. To do this, we use the Marshal API as follows:

C#
// Serialize our raw string data into a binary stream
BinaryFormatter b = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
b.Serialize(stream, raw);
stream.Flush();
int dataSize = (int)stream.Length;

// Create byte array and transfer the stream data
byte[] bytes = new byte[dataSize];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(bytes, 0, dataSize);
stream.Close();

// Allocate a memory address for our byte array
IntPtr ptrData = Marshal.AllocCoTaskMem(dataSize);

// Copy the byte data into this memory address
Marshal.Copy(bytes, 0, ptrData, dataSize);

With the string data now in memory, referenced by our ptrData pointer in the above code, we can create our COPYDATASTRUCT instance and populate the lpData and dwData members accordingly. So, now that we've wrapped our message up as a COPYDATASTRUCT object, we're ready to send this to another Window using the SendMessage API. However, to do this we first need to know which applications should receive the data, i.e. which are listening and on the correct channel. Also, what if the application doesn't have a Window handle to send our message to?

To overcome this, we use some native Window properties and our XDListener class. When an instance of the class is invoked, it creates a hidden window on the desktop which acts as listener for all Windows messages. This is done by extending the NativeWindow class of System.Windows.Forms. By overriding the WndProc method, this allows us to filter Windows messages and look for our WM_COPYDATA message containing the message data.

The XDListener class also makes use of Window properties to create property flags indicating which channels the instance is listening on, and therefore which messages it should receive. When a message is broadcast, it enumerates all of the desktop Windows using the EnumChildWindows Win32 API. It looks for a flag (property name) on the window that represents the channel name. If found, the Windows WM_COPYDATA message is sent to that window. Once there, it will be caught and processed by the XDListener instance that owns the hidden window. To read the message data, we use the lParam of the native Windows message in order to expand the COPYDATASTRUCT instance. From this, we can locate and restore the original string message which was stored in memory earlier.

C#
// NativeWindow override to filter our WM_COPYDATA packet
protected override void WndProc(ref Message msg)
{
    // We must process all the system messages and propagate them
    base.WndProc(ref msg);
    
    // If our message
    if (msg.Msg == Win32.WM_COPYDATA)
    {
        // msg.LParam contains a pointer to the COPYDATASTRUCT struct
        Win32.COPYDATASTRUCT dataStruct = 
            (Win32.COPYDATASTRUCT)Marshal.PtrToStructure(
            msg.LParam , typeof(Win32.COPYDATASTRUCT));
        
        // Create a byte array to hold the data
        byte[] bytes = new byte[this.dataStruct.cbData];
        
        // Make a copy of the original data referenced by 
        // the COPYDATASTRUCT struct
        Marshal.Copy(this.dataStruct.lpData, bytes, 0, 
            this.dataStruct.cbData);
        // Deserialize the data back into a string
        MemoryStream stream = new MemoryStream(bytes);
        BinaryFormatter b = new BinaryFormatter();
        
        // This is the message sent from the other application
        string rawmessage = (string)b.Deserialize(stream);
        
        // do something with our message
    }
}

Note that because the message is stored in memory whilst it's broadcast to other applications, we must remember to free that memory after the message has been sent. Each Window receiving the data will make its own copy, so the original data can be destroyed safely as soon as the messages have been sent. This is necessary because the data is stored in unmanaged memory and would otherwise result in a memory leak.

C#
// Free the memory referenced by the given pointer
Marshal.FreeCoTaskMem(lpData);

Below are the other PInvoke methods used for setting and removing Window properties, as well as enumerating the desktop Windows.

C#
// Delegate used during window enumeration
public delegate int EnumWindowsProc(IntPtr hwnd, int lParam);

// The Win32 API used to enumerate children of the desktop window 
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr hwndParent, 
    EnumWindowsProc lpEnumFunc, IntPtr lParam);

// The API used to look for a named property on a window
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int GetProp(IntPtr hwnd, string lpString);

// The API used to set a named property on a window, and 
// hence register a messaging channel
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int SetProp(IntPtr hwnd, string lpString, int hData);

// The API used to remove a property from a window, and hence unregister a 
// messaging channel
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int RemoveProp(IntPtr hwnd, string lpString);

Further Reading

History

  • Feb 2007: Initial release
  • 25th Feb, 2007: Added VB port to demo
  • 29th May, 2007: Article edited and posted to the main CodeProject.com article base
  • 2nd June, 2008: Improved threading support to avoid application hanging

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)