1. 程式人生 > >在MFC程式中顯示WPF視窗

在MFC程式中顯示WPF視窗

    最近想要在原有系統(基於MFC,非託管)中加入WPF的介面。搜尋了一段時間,發現大部分文章都是在談託管程式C++中呼叫WPF,還是不太適合我的需要。於是自己嘗試著從本機C++的MFC程式中呼叫WPF,使用C# 實現一個COM元件作為中間層。目標是在MFC程式中彈出一個WPF視窗。

  • 建立WPF UserControl library工程
     新增一個Window,命名為MainWindow,實現具體的介面。
  • 建立C# Library工程

    在工程中新增以下引用:

    • WindowsBase
    • PresentationCore
    • PresentationFramework
    • System.Xaml
    • 上面的WPF工程

     新增using System.Runtime.InteropServices;

     定義介面:ShowMainWindow.

     程式碼如下:

<!--<br/ /> <br/ /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ /> http://www.CodeHighlighter.com/<br/ /> <br/ /> -->[Guid(
"B5229C49-F49D-4A2C-A9F5-CA1249DE3890")]//使用工具生成的GUIDpublicinterface UI_Interface
{
    [DispId(
1)]
    
void ShowMainWindow();
}
  • 實現介面 ExpandedBlockStart.gif程式碼 <!--<br/ /> <br/ /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ /> http://www.CodeHighlighter.com/<br/ /> <br/ /> -->[Guid(
    "85512BED-C76D-4163-9454-F32EE634C4B2"),//使用工具生成的GUIDClassInterface(ClassInterfaceType.None),
    ComSourceInterfaces(
    typeof(UI_Events))]
    publicclass UI_Class : UI_Interface
    {
        
    publicvoid ShowMainWindow()
        {
            MainWindow main 
    =new MainWindow();
            main.ShowDialog();
        }
    }
  • 註冊COM介面

     生成強名稱檔案

          sn –k UI_Interface.snk

     在AssemblyInfo.cs中,新增下面一行

          [assembly: AssemblyKeyFile("UI_Interface.snk")]

     將dll加入GAC

       gacutil /i UIInterface.dll
    註冊
     REGASM UIInterface.dll
  • 在MFC中新增程式碼,呼叫COM元件
     引用COM元件
     #import “<Full Path>\UIInterface.tlb"
     新增呼叫程式碼:
<!--<br/ /> <br/ /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ /> http://www.CodeHighlighter.com/<br/ /> <br/ /> -->CoInitialize(NULL);
UI_InterfacePtruiInterfacePtr;
HRESULThr
= uiInterfacePtr.CreateInstance(__uuidof(UI_Class));

if(hr== S_OK)
{
    uiInterfacePtr
->ShowMainWindow();
}

CoUninitialize();