MFC调用WPF函数

来源:互联网 发布:ubuntu安装nodejs 编辑:程序博客网 时间:2024/05/18 22:54

1建立WPF工程
建立一个WPF工程,命名为WPFforMFC;
修改MainWindow.xaml代码:

<Window x:Class="WPFforMFC.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow" Height="350" Width="525"><Window.Background>    <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">        <GradientStop Color="Yellow" Offset="0.0"/>        <GradientStop Color="Red" Offset="0.25"/>        <GradientStop Color="Blue" Offset="0.75"/>        <GradientStop Color="LightBlue" Offset="1.0"/>    </LinearGradientBrush></Window.Background><TextBlock Text="Hello WPF!" HorizontalAlignment="Center" VerticalAlignment="Center"FontSize="21" Width="116" /></Window>

2建立MFC工程
建立一个基于对话框的MFC工程,名为CallWPF;

在CallWPF上右键-》属性-》配置属性-》常规,将“公共语言运行时”该为“公共语言运行时支持(/clr)”;

在CallWPF上右键-》属性-》通用属性-》框架和引用,点击添加新引用,选择“项目”下的“WPFforMFC”,并确定;

在CallWPF上右键-》属性-》通用属性-》框架和引用,点击添加新引用,选择“.NET”下的“PresentationCore”、“PresentationFramework”、“WindowBase”(不能同时选择,一次只能添加一个),并点击确定;

3调用
在MFC项目的头文件文件夹中加入一个.h文件,命名为host.h。
在host.h中加入代码:

using namespace System::Windows;ref class WPFHost{    public:    static WPFforMFC::MainWindow^ WPFWindow;    //WPFforMFC需要跟你的WPF工程名字一致,下同};void ShowWPFWindow(){    WPFHost:: WPFWindow= gcnew WPFforMFC::MainWindow();    WPFHost:: WPFWindow->ShowDialog();}

在CallWPFDlg.cpp中引入头文件“host.h”;
在Dialog的“确定”按钮的Click函数中加入代码:

ShowWPFWindow();

4说明
ref : 创建一个对于在托管堆中对象的应用(reference class)
“^”: 追加到引用类型的声明中
C++/CLI中使用gcnew关键字表示在托管堆上分配内存,并且为了与以前的指针区分,用^来替换* ,就语义上来说他们的区别大致如下:
  1. gcnew返回的是一个句柄(Handle),而new返回的是实际的内存地址.
  2. gcnew创建的对象由虚拟机托管,而new创建的对象必须自己来管理和释放.
微软官方解释:
gcnew creates an instance of a managed type (reference or value type) on the garbage collected heap. The result of the evaluation of a gcnew expression is a handle (^) to the type being created.
gcnew 创建了一个实例在GC堆上,导致的结果就是一个句柄类型已经被创建。
5运行结果
这里写图片描述
这里写图片描述

0 0
原创粉丝点击