从DLL控制WPF应用程序(进程间通信)

时间:2014-06-18 10:54:58

标签: c# .net wpf dll

我有一个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函数。

怎么可能?

1 个答案:

答案 0 :(得分:0)

最后我决定使用一个简单的消息库,因为我可以在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,因为我没有发送大量数据,只是控制消息应用程序。