在MFC程式中顯示WPF視窗
阿新 • • 發佈:2019-02-08
最近想要在原有系統(基於MFC,非託管)中加入WPF的介面。搜尋了一段時間,發現大部分文章都是在談託管程式C++中呼叫WPF,還是不太適合我的需要。於是自己嘗試著從本機C++的MFC程式中呼叫WPF,使用C# 實現一個COM元件作為中間層。目標是在MFC程式中彈出一個WPF視窗。
- 建立WPF UserControl library工程
- 建立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({
[DispId(1)]
void ShowMainWindow();
}
- 實現介面
程式碼
<!--<br/ />
<br/ />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />
http://www.CodeHighlighter.com/<br/ />
<br/ />
-->[Guid(
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();