Posted by: Zeeshan Amjad | November 1, 2009

Calling WPF from VC++ Program


Previously we saw that how can we call the Unmanaged dialog from WPF, now we are going to do the reverse and calling the WPF from the win32 application. For calling WPF dialog, we have to compile our project with /CLR switch and include all the proper references of the required DLL. In addition we also include the proper namespaces in our VC++ program. Here is the simple VC++ program to call the WPF dialog.

  1: #include <windows.h>
  2: 
  3: using namespace System;
  4: using namespace System::Windows;
  5: 
  6: [STAThread]
  7: int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
  8: 				   LPSTR lpcStr, int nCmd)
  9: {
 10: 	Window^ win = gcnew Window();
 11: 	win->Title = "WPF Window";
 12: 	win->Height = 300;
 13: 	win->Width = 400;
 14: 	win->Content = "This is WPF Window";
 15: 	win->ShowDialog();
 16: 	return 0;
 17: }
 18: 

Here is the output of this program.

WPFVC

If we want to make our Win32 window as a parent of this window then we can’t directly set the handle of window as an owner of this window. We first have to create an object of WindowInteropHelper class and pass the WPF window as a parameter to the constructor and then use IntPtr to set the owner of the WPF window. These are defined in System::Windows::Interop namespace. Here is simple code to demonstrate this.

  1: Window^ win = gcnew Window();
  2: Windows::Interop::WindowInteropHelper^ wih = gcnew Windows::Interop::WindowInteropHelper(win);
  3: wih->Owner = IntPtr(hWnd);
  4: 
Advertisements

Responses

  1. […] WPF Dialog from Unmanaged Code We have already saw example of calling WPF dialog from VC++ here. But in that program we compile our VC++ program with /clr switch. It means our VC++ program is […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: