Как передать данные из одного приложения WPF в другое приложение WPF? - PullRequest
0 голосов
/ 29 марта 2019

У меня есть два приложения: Cashier.exe и Payment.exe

Я хочу передать данные для PosWindows.retrieveOrder из Cashier.exe в Payment.exe

PosWindows.retrieveOrder содержитмного данных, таких как OrderId, OrderCode и более (что означает не единичные данные)

Я использую этот код, но он не отправляет данные.потому что он не может отправить целые данные, как это?

ProcessStartInfo psi = new ProcessStartInfo();
                    psi.FileName = "C:/Project/Application/Payment/Payment.exe";
                    psi.Arguments = "\"" + PosWindows.totalAmount.ToString() + "\"\"" + PosWindows.retrieveOrder + "\"";
                    var p = Process.Start(psi);

Если я только отправлю PosWindows.totalAmount.ToString().

, что-то вроде этого

 ProcessStartInfo psi = new ProcessStartInfo();
                    psi.FileName = "C:/Project/Application/Payment/Payment.exe";
                    psi.Arguments = "\""+ PosWindows.totalAmount.ToString() + "\"";
                    var p = Process.Start(psi);

все работает нормально.но когда я добавляю PosWindows.retrieveOrder, он не работает.

imagePosWindows.retrieveOrder is not empty for sure">

делает невозможным отправку PosWindows.retrieveOrder?

ДонНе знаю, возникла ли эта проблема из приведенного ниже кода (потому что я не объявляю для retrieveOrder)

Этот файл на Payment.exe

 private void app_Startup(object sender, StartupEventArgs e)
    {
        var args = e.Args;
        if (args != null && args.Count() > 0)
        {
            foreach (var arg in args)
            {
                PaymentView.globalTotalAmount = decimal.Parse(arg);


            }
        }
    }

, если дачто мне делать ?Я имею в виду, что я должен поставить, чтобы заменить эту часть decimal.Parse(arg) для retrieveOrder?

1 Ответ

0 голосов
/ 29 марта 2019

Вы можете использовать NamedPipeServerStream class.

https://docs.microsoft.com/en-us/dotnet/api/system.io.pipes.namedpipeserverstream?view=netframework-4.7.2

Возьмите одно из ваших приложений в качестве клиента, а другое - в качестве сервера. Вы можете обрабатывать асинхронную связь и анализировать ваше сообщение, когда прослушивание завершено.

Также вы можете проверить Пример именованных каналов

Изменить для примера решения:

В клиентском приложении давайте вызовем класс PipeClient.cs

    public void Send(string SendStr, string PipeName, int TimeOut = 1000)
    {
        try
        {
            NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", PipeName, PipeDirection.Out, PipeOptions.Asynchronous);

            // The connect function will indefinitely wait for the pipe to become available
            // If that is not acceptable specify a maximum waiting time (in ms)
            pipeStream.Connect(TimeOut);
            Debug.WriteLine("[Client] Pipe connection established");

            byte[] _buffer = Encoding.UTF8.GetBytes(SendStr);
            pipeStream.BeginWrite(_buffer, 0, _buffer.Length, AsyncSend, pipeStream);
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Pipe Send Exception: " + ex);
        }
    }


    private void AsyncSend(IAsyncResult iar)
    {
        try
        {
            // Get the pipe
            NamedPipeClientStream pipeStream = (NamedPipeClientStream)iar.AsyncState;

            // End the write
            pipeStream.EndWrite(iar);
            pipeStream.Flush();
            pipeStream.Close();
            pipeStream.Dispose();
        }
        catch (Exception oEX)
        {
            Debug.WriteLine(oEX.Message);

        }
    }

И после инициализации вашего класса просто отправьте сообщение с:

_pipeClient.Send(pipeMsg, "PipeName", Timeout);

В серверном приложении давайте вызовем класс PipeServer.cs

    public void Listen(string PipeName)
    {
        try
        {
            // Set to class level var so we can re-use in the async callback method
            _pipeName = PipeName;
            // Create the new async pipe 
            NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

            // Wait for a connection
            pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
        }
        catch (Exception oEX)
        {
            Debug.WriteLine(oEX.Message);
        }
    }

    private void WaitForConnectionCallBack(IAsyncResult iar)
    {
        NamedPipeServerStream pipeServer = (NamedPipeServerStream)iar.AsyncState;
        try
        {
            // End waiting for the connection
            pipeServer.EndWaitForConnection(iar);

            byte[] buffer = new byte[255];

            // Read the incoming message
            pipeServer.Read(buffer, 0, 255);

            // Convert byte buffer to string
            string stringData = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            Debug.WriteLine(stringData + Environment.NewLine);

            // Pass message back to calling form
            PipeMessage.Invoke(stringData);

            // Kill original server and create new wait server
            pipeServer.Close();
            pipeServer = null;
            pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

            // Recursively wait for the connection again and again....
            pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
        }
        catch (Exception ex)
        {
            string ctch = ex.ToString();
            return;
        }
    }

Для обработки сообщения pipestream делегируйте обработчику и анализируйте сообщение:

_pipeServer.PipeMessage += new DelegateMessage(PipesMessageHandler);

где-то, что вам нужно в вашем коде:

_pipeServer.Listen("PipeName");

и анализ, например:

private void PipesMessageHandler(string message) 
{
    if (this.Dispatcher.CheckAccess())
    {
        this.Dispatcher.Invoke(new NewMessageDelegate(PipesMessageHandler), message);
    }
    else
    { 
        string pipeMessage = Convert.DateTime(message);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...