簡體   English   中英

如何在C#中的兩個程序之間發送數據?

[英]How can I send data between two programs in C#?

我有兩個應用程序 - > App1和App2。 App1通過使用System.Diagnostic.Process()傳遞一些命令行參數來打開App2。 用戶現在可以訪問App2。

但是,當用戶在App1中更改某些命令參數時,我需要打開現有的應用程序(App2)而不使用新參數關閉它。

我怎樣才能做到這一點?

任何反饋都會有所幫助。

另一種選擇可能是基於WCF的解決方案。 請參閱WCF聊天示例

你應該使用IPC。 有關一些有用的鏈接,請參閱C#中的IPC機制 - 用法和最佳實踐

為什么不使用套接字(客戶端和服務器)的普通舊TCP / IP。

你想做的事情並不是直截了當的。 在.net中執行預先打包的方法稱為Remoting ,它內置於框架中並允許IPC(進程間調用)。

根據您的經驗水平,您可能更好地推出自己的簡化版本。 例如,讓兩個程序使用文件傳遞數據。

App1將參數寫入文本文件(XML,Delimited,您真正的選擇)。

在App2上有一個定時器,每隔10秒喚醒一次,並檢查是否有新的參數文件。 如果是這樣,它會消耗它並刪除文件。

UPDATE
正如John Saunders正確指出的那樣,Remoting已被WCF取代,但Remoting上仍有大量信息,這可能不是一個糟糕的開始。

我將使用WindowsFormsApplicationBase類(來自Microsoft.VisualBasic程序集)和Program.cs文件中的以下代碼:

using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;

namespace TestSolution
{
    sealed class Program : WindowsFormsApplicationBase
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] commandLine)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var program = new Program()
            {
                IsSingleInstance = Properties.Settings.Default.IsSingleInstance
            };

            // Here you can perform whatever you want to perform in the second instance

            // After Program.Run the control will be passed to the first instance    
            program.Run(commandLine);
        }

        protected override void OnCreateMainForm()
        {
            MainForm = new ImportForm();
        }

        protected override bool OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            // This code will run in the first instance

            return base.OnStartupNextInstance(eventArgs);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM