COM类和WPF应用程序之间的双向消息

时间:2015-08-25 16:34:30

标签: c# wpf com interop

我有一个WPF应用程序,我构建为dll并从c#开发的COM类(MyComClass)运行,如下所示。

    private void runDlg()
    {
        m_app = new Application();
        m_app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
        m_appRunning = true;
        m_app.Run();
    }

    public void Open()
    {
        if(m_appRunning && !m_windowOpen)
        {
            m_app.Dispatcher.Invoke(new Action( () => new EwokApp().Show() ) );
            Thread.Sleep(cWaitPeriod1000_ms);
            m_windowOpen = true;
        }
    }

然后我将消息从COM类传递到WPF应用程序,如下所示

    [DllImport("User32.dll", EntryPoint = "FindWindow")]
    public static extern Int32 FindWindow(String lpClassName, String lpWindowName);

    [DllImport("User32.dll", EntryPoint = "SendMessage")]
    public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);

    public void Start()
    {
        if(m_windowOpen)
        {
            int hWnd = FindWindow(null, "MY-WPF-APP");
            if(hWnd != 0)
            {
                m_msgHelper.sendMessage(hWnd, WM_START, 0, 0);
                Thread.Sleep(cWaitPeriod2000_ms);
            }
        }
    }

在我的WPF应用程序中,我创建了一个消息处理程序,如下所示

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {   
        HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
        source.AddHook(new HwndSourceHook(WndProc));  
    }

    private static IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        // address the messages you are receiving using msg, wParam, lParam
        if (msg == WM_START)
        {
            MyApp window = (MyApp)HwndSource.FromHwnd(hWnd).RootVisual;
            window.start();
        }        
        return IntPtr.Zero;
    }

通过获取WPF窗口的处理程序并将其传递给SendMessage函数,我可以成功地从COM类将消息发布到应用程序。

我还希望WPF应用程序获取创建它的COM类的处理程序并向其发布消息。有人可以建议如何做到这一点。

由于

0 个答案:

没有答案