Passing Information Between Applications in C#

血红的双手。 提交于 2019-11-29 14:49:07

You have multiple choices for IPC(Inter Process Communication) such as: Mailslot, NamedPipe, Memory Mapped File, Socket, Windows Messaging, COM objects, Remoting, WCF... http://msdn.microsoft.com/en-us/library/windows/desktop/aa365574(v=vs.85).aspx http://en.wikipedia.org/wiki/Inter-process_communication

Some of them provide two-way communication, some needs considaration about system security(antivirus & firewall restrictions, you need to add the application as an exception in their settings).

Sending message through WM_COPYDATA can be done just by SendMessage, PostMessage is not supported, it means that the communication is sync.

Using outproc singleton COM object is another way, its not as simple as the other ways and both app. must be run on the same security context to access the same COM object.

Launching a separate application can coz some restrictions in communication methods or types of data you can pass, but separation of them will also protect them from their failures(App. crash will not close the other one).

If the two parts are always run on the same PC, using one of them as dll[inproc] is simpler. Using other techniques such as Socket, Remoting, WCF will provide you with more flexibility for communication, i.e. the two parts can run in different PCs with minor modifications...

Another way of accomplishing intra-app communication is with the use of Windows messages. You define a global windows message id and use Windows API calls such as SendMessage and PostMessage.

Here's a simple article that explains how: Ryan Farley's article "Communication between applications via Windows Messages"

This is in effect the observer pattern, receiving all the Windows messages being directed at the current Window and picking out the one you're listening out for.

In my experience this is definitely less flaky than the clipboard approach.

If you need a simple way to do an outproc communication of two WinForms applications, then why don't you use the Clipboard with a custom format?

In the source application:

    // copy the data to the clipboard in a custom format
    Clipboard.SetData( "custom", "foo" );

In the destination application, create a timer to peek the clipboard:

    private void timer1_Tick( object sender, EventArgs e )
    {
        // peek the data of a custom type
        object o = Clipboard.GetData( "custom" );
        if ( o != null )
        {
            // do whatever you want with the data
            textBox1.Text = o.ToString();
            // clear the clipboard
            Clipboard.Clear();
        }
    }

This should fit your needs and it's still really simple as it doesn't require any heavyweight outproc communication mechanisms.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!