Living .NET...

Musings on .NET, and the like - Manoj G [MVP, Connected Systems Developer]

Sharing data between two applications - the easiest way!

Can you tell me what is the easiest way (minimal coding effort) to share data (memory) between two applications/processes on the same machine ? Lemme give you a couple of hints.

It is not:
 1) Remoting
 2) Pipes
 3) MMF (Memory Mapped Files)
 4) DCOM

And the final hint, we cannot survive in this industry without it (literally).

You guessed it right!

The cornerstone of an average developer's high productivity at work (CTRL-C, CTRL-V!) - The Clip Board.

The Windows clip board is accessible through System.Windows.Forms.Clipboard class. We can use the SetDataObject shared method to add objects to the clipboard (lets call it CB).  Likewise, we can use GetDataObject to retrieve contents from the CB.  We can also serialize complex objects like the DataSet and store it in the CB for consumption.

Though this approach is simple, it is definitely not elegant, as the clipboard is something that all applications can access. Hence, we cannot ensure a a reliable sharing (for instance, using Outlook, I can purge the CB).  For reliable sharing of information, we can use one of the methods metioned in the beginning of the post.

Here's a sample code snippet using the ClipBoard:

If Environment.CommandLine.IndexOf("-Put") > 0 Then
  
System.Windows.Forms.Clipboard.SetDataObject("Hello from here", True)
Else
      Dim 
iData As System.Windows.Forms.IDataObject = Clipboard.GetDataObject()

      
If iData.GetDataPresent(DataFormats.StringFormat) Then
          
Console.WriteLine(iData.GetData(DataFormats.StringFormat))
      
Else
         
Console.WriteLine("Could not retrieve data off the clipboard.")
      
End If
End If

It is noteworthy (obvious actually) that the clipboard is extensively used in windows applications in the implementations of Drag - Drop, Cut /Copy - Paste etc.

Posted: Jan 22 2004, 10:38 AM by Manoj G | with no comments
Filed under:
Leave a Comment

(required) 

(required) 

(optional)

(required)