【问题标题】:Controlling a WPF app from a DLL (interprocess communication)从 DLL 控制 WPF 应用程序(进程间通信)
【发布时间】:2014-06-18 10:54:58
【问题描述】:

我有一个 dll 必须与不是用 C# 编写的程序通信。我已经用这段代码建立了这种联系:

namespace ClassLibrary1
{
    public class Class1
    {
        [DllExport("teststring", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        [return: MarshalAs(UnmanagedType.BStr)]
        public static String TestString(string test)
        {
            return "Test" + test;
        }

    public static CallbackProc _callback;

    [DllExport("SetCallback", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
    public static void SetCallback(CallbackProc pCallback)
    {
      _callback = pCallback;
      //var app = new App();
      //var win = new MainWindow();
      //app.Run(win);
      MessageBox.Show("C#: SetCallback Completed");
    }

    [DllExport("TestCallback", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
    public static void TestCallback(string passedString)
    {
      string displayValue = passedString;
      string returnValue = String.Empty;

      TodayButton.MainWindow app = new TodayButton.MainWindow();
      app.InitializeComponent();

      MessageBox.Show("C#: About to call the Callback. displayValue=" + displayValue + ", returnValue=" + returnValue);
      _callback(displayValue, ref returnValue);
      MessageBox.Show("C#: Back from the Callback. displayValue=" + displayValue + ", returnValue=" + returnValue);
    }

    public delegate void CallbackProc( [MarshalAs(UnmanagedType.BStr)] String PassedValue,  [MarshalAs(UnmanagedType.BStr)] ref String ReturnValue);

  }

}

所以回调工作完美。我有一个问题,我不知道如何解决。
我想将其用作我的 WPF 应用程序的界面。因此,当程序调用 dll 时,dll 应该启动 WPF 应用程序并等待该应用程序关闭并发送信息,然后我会调用回调。

问题是我不想在每次需要信息时启动和停止 WPF 应用程序。我想要一个按钮“发送到回调”。问题是这个项目是一个类库,使用 DllExport 并且 WPF 项目不会编译为类库。

有没有办法做到这一点,所以我可以用 dll 控制整个 WPF 应用程序?所以我将控制开始、停止、传递回调值,以便我可以从 WPF 表单中调用它们,或者当我按下 WPF 中的按钮时将信息发送回TestCallback 函数。

这怎么可能?

【问题讨论】:

标签: c# .net wpf dll


【解决方案1】:

最后我决定使用一个简单的消息传递库,因为我可以在 DLL 端使用 WinForms,在另一端使用 WPF,这样我就可以使用 Windows 消息。 http://thecodeking.github.io/XDMessaging.Net/ 是我使用的库。

另一种更高级的数据共享方式是http://blogs.msdn.com/b/dmetzgar/archive/2012/10/16/an-updated-custom-wcf-transport-channel-example.aspx 我想使用它,但最后我决定不使用 WCF,因为我不会发送大量数据,只是控制应用程序的消息.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多