先提一下,gcnew关键字被用于建立一个管制类型的实例,在本例中将建立一个垃圾回收集合栈的实例。所有被gcnew分配的内存空间将被垃圾回收器自动管理,而开发人员并不需要为什么时间释放它们而操心。
为了使用WPF程序,关键是System::Windows::Interop::HwndSource类。这个类将在Win32窗口中使用WPF程序,因此,WPF程序可以作为MFC窗口的子窗口放到UI上。而在WPF对象和Win32窗口之间的通讯要通过引用C++程序中被的静态字段。这些静态字段的代码如下:
ref class Globals{public:static System::Windows::Interop::HwndSource^ gHwndSource;static WPFControls::AnimClock^ gwcClock;};
HWND GetHwnd(HWND parent, int x, int y, int width, int height){System::Windows::Interop::HwndSourceParameters^ sourceParams = gcnew System::Windows::Interop::HwndSourceParameters("MFCWPFApp");sourceParams->PositionX = x;sourceParams->PositionY = y;sourceParams->Height = height;sourceParams->Width = width;sourceParams->ParentWindow = IntPtr(parent);sourceParams->WindowStyle = WS_VISIBLE | WS_CHILD;Globals::gHwndSource = gcnew System::Windows::Interop::HwndSource(*sourceParams);DateTime tm = DateTime::Now;Globals::gwcClock = gcnew WPFControls::AnimClock();Globals::gwcClock->ChangeDateTime(tm.Year,tm.Month,tm.Day,tm.Hour,tm.Minute,tm.Second);FrameworkElement^ myPage = Globals::gwcClock;Globals::gHwndSource->RootVisual = myPage;return (HWND) Globals::gHwndSource->Handle.ToPointer();}
void RefreshWPFControl(){FrameworkElement^ page;DateTime tm = DateTime::Now;Globals::gwcClock->ChangeDateTime(tm.Year,tm.Month,tm.Day,tm.Hour,tm.Minute,tm.Second);page = Globals::gwcClock;Globals::gHwndSource->RootVisual = page;return;}
int CMFCHostWPFDlg::OnCreate(LPCREATESTRUCT lpCreateStruct){if (CDialog::OnCreate(lpCreateStruct) == -1)return -1;hwndWPF = GetHwnd(this->GetSafeHwnd(), 20, 28, 205, 130);return 0;}