Previous month:
March 2010
Next month:
July 2010

April 2010

MFC and WPF Interop

Nowadays still many MFC applications exist. And maybe there’s no reason to rewrite the application as MFC gets big improvements with Visual Studio 2010. With that in mind it would be great to integrate WPF controls within MFC. Of course that’s possible!

Interoperability between MFC and WPF is based on two major features:

  • Managed and native code interop
  • Window handles to WPF elements

Using managed and native code in a mixed way can be done with C++/CLI. C++/CLI allows using managed code from native classes and the other way around. Instead of extending the C++ language with keywords starting with __ (which was done with Managed C++), C++/CLI is a syntax that extends C++ with managed keywords such as ref to define a managed ref type, value to define a managed value type, and gcnew to allocate an object on the managed heap. The C++/CLI syntax was already discussed in some older blog entries that are referenced below, and some new ones will follow.

So the first step on MFC and WPF interop are

  • Create a WPF library, e.g. with a user control
  • Create a MFC application
  • Add Common Language Runtime support to the MFC application (Configuration Properties -> General)
  • Reference the necessary assemblies (Common Properties –> Framework and References)
    • At least these should be: System, PresentationCore, PresentationFramework, WindowsBase, and of course the assembly holding the user control.

Interoperability with WPF is done by creating and using Window handles to the WPF control.

To do this the .NET class HwndSource from the System.Windows.Interop namespace represents a WPF control in a Win32 window. This class derives from the base class PresentationSource that is an abstract class that can be used to map different technologies to WPF. HwndSource is the concrete class to offer Window handles.

The base class PresentationSource provides several static methods and properties to get and enumerate presentation sources. Presentation sources are added and removed by a derived class that invokes the base class members AddSource and RemoveSource.

HwndSource implements a Windows handle to wrap a Visual object that is a base class of WPF elements. Settings that can be assigned to the HwndSource are the position, height and width, the parent window, and window class styles.

The following code snippet shows the method GetUserControl1Hwnd that is implemented as a private member of the MFC dialog class. In this method a WPF control is instantiated, and this is assigned to the RootVisual property of the HwndSource object. The configuration of the new window is defined by setting the position, height, and width, the parent window, and the window class style. HwndSource can be configured by passing HwndSourceParameters to the constructor (as it is done in this code snippet), or passing separate values to a constructor overload. If the Window handle is needed, the HwndSource class defines the Handle property that returns an IntPtr. With this structure the ToPointer method returns a void*.

HWND CMFCDialogAppDlg::GetUserControl1Hwnd(HWND parent, int x, int y, int width, int height)
HwndSourceParameters^ sourceParams = gcnew HwndSourceParameters("MFCWPFApp");
sourceParams->PositionX = x;
sourceParams->PositionY = y;
sourceParams->Height = height;
sourceParams->Width = width;
sourceParams->ParentWindow = IntPtr(parent);
sourceParams->WindowStyle = WS_VISIBLE | WS_CHILD;
m_hwndSource = gcnew HwndSource(*sourceParams);

m_wpfUC = gcnew UserControl1();

m_hwndSource->RootVisual = m_wpfUC;

return (HWND) m_hwndSource->Handle.ToPointer();

For keeping a reference to a managed object in a unmanaged class (for example a reference to the WPF user control within the MFC dialog), it must be taken care of that the garbage collector does not release the managed object because no managed reference exists to it. Keeping the managed object can be done with the GCHandle structure that is a .NET value type from the namespace System.Runtime.InteropServices. GCHandle defines the static method Alloc that allocates and returns a GCHandle to a .NET objects. The instance method Free releases the reference to the object. The method ToIntPtr returns a native pointer that can be used by API methods.

Instead of using GCHandle directly, a gcroot object can be declared as a member of the class. gcroot is a native type defined within <vcclr.h> and wraps GCHandle for easy use. The constructor of this class allocates the GCHandle, and the destructor releases it.

gcroot here is used to define members to the WPF user control in the native dialog class.

gcroot<HwndSource^> m_hwndSource;
gcroot<UserControl1^> m_wpfUC;

Finally, the method GetUserControl1Hwnd where the WPF user control is instantiated is invoked on creation of the dialog. The first argument defines the parent window which is the window of the dialog itself. The method GetSafeHwnd of the base class CWnd returns the member m_hWnd, the window handle that is attached to the dialog or NULL.

int CMFCDialogAppDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
if (CDialogEx::OnCreate(lpCreateStruct) == -1)
return -1;

m_hwndWPF = GetUserControl1Hwnd(this->GetSafeHwnd(), 20, 20, 200, 150);

return 0;

Now the WPF user control is created and assigned as a child window to the dialog. The members of the WPF control can be easily invoked by using the reference to the managed object.

Older blog entries about C++/CLI:

More information on C++/CLI and interop between native and managed code in my Take off to C++/CLI workshop.


Developer Day 2010

Am 27. April gibt es zum vierten mal den Developer Day in Wien. Diesmal steht dieser Tag im Zeichen von Visual Studio 2010 und .NET 4. Es gibt neue Informationen zu Änderungen bei .NET 4, zeigt einen Application Lifecycle mit Visual Studio 2010, Neuerungen bei C# 4, Informationen zu Threading, der Task Parallel Library, Parallel LINQ wie auch Coordination data structures… Neuigkeiten gibt es auch zu ASP.NET AJAX und JQuery. Natürlich fehlt auch nicht Silverlight 4 und Windows Azure bei den Themen. Ein besoneres Hightlight ist auch das Windows Phone 7!

Ich hoffe möglichst viele dort zu sehen!

Informationen zu der Agenda und zur Anmeldung:


Visual Studio 2010 Launch

Visual Studio 2010 and .NET 4 is released! Download it from MSDN! I’m already running it on my systems.

The Visual Studio release candidate was faster than the Beta 2 version, the release is faster once more!

What’s new with .NET 4 and Visual Studio 2010, why should you switch? .NET 4 has not big-bang new features like we’ve seen with .NET 3 (WPF, WCF, WF), and .NET 3.5 (LINQ), but stabilizing and enhancements in many different areas. New controls and enhancements with WPF, easier configuration with WCF, a complete new WF runtime and library… A major focus on the enhancements on C# 4 is easier integration of dynamic languages. The Managed Extensibility Framework (MEF) allows easier hosting and connecting add-ins compared to MAF, ASP.NET MVC gives a new programming model for Web applications, and of course there are parallel computing enhancements – tasks, Parallel LINQ, coordination data structures…

Of course this is not the full list of features of .NET 4. Nearly every application can get cool things out of the new release.

You can read all about the new things in my new book Professional C# 4 and .NET 4.


In case you are still restricted in using .NET 3.5 or .NET 3 or .NET 2 because of deployment restrictions…. You still should think about switching to Visual Studio 2010! You can target the older .NET runtimes with the new version of Visual Studio and get big improvements on the WPF designer, lot of features on debugging and analyzing the application…

If you are in Vienna on 27-April, you can hear about many of the new features at the Developer Day 2010!

See you there!


Enumerating Files and Directories with .NET 4.0

With .NET 4 the Directory and DirectoryInfo classes have been extended to allow for enumerated access to filenames and directories. EnumerateFiles, EnumerateDirectories, and EnumerateFileSystemEntries are the new methods to enumerate files, directories, and both files and directories. Instead of retrieving all file system entries before they can be used, with the new methods an enumerator is offered to access the file system and retrieve the filenames during the loop of a foreach statement. This is cool for not having to wait until all the filenames are retrieved. The older methods GetFiles, GetDirectories, and GetFileSystemEntries returned a string[] and thus the result could only be used as soon as the method was finished.

The new methods have three overloads to specify a search pattern and search options beside the path where the search starts. With the SearchOption enumeration it can be specified if only the top directory (TopDirectoryOnly) should be accessed, or the complete directory tree (AllDirectories).

var files = Directory.EnumerateFiles(@"\\server\share", "*", SearchOption.AllDirectories).Take(10);
foreach (var file in files)

As IEnumerable<string> is returned from these methods, they can also be used with all the LINQ methods and in a LINQ query.

There’s one important restriction with the new methods. The new API cannot be used to search through the complete disk because with directories that cannot be accessed an exception of type UnauthorizedAccessException is thrown and the enumeration stops. The reason for this is that the methods are designed similar to the existing methods that returned a string array. In a future version a search option such as ContinueOnError might be added as described on the Microsoft Connect site. If this is a feature you want, please vote at the Connect site.

More information on .NET 4 in my new book Professional C# 4 with .NET 4 and in my Take off to .NET 4 workshop.


EU against Silverlight?

After the  browser war from the European Union against Microsoft seems to be solved by Microsoft offering a browser ballot from Windows Update, it seems a new case against Microsoft might be opened. Some vendors demand the EU should open a new case against Microsoft as they fear Silverlight gains a big market share. They demand the EU to restrict Silverlight options. shows a day-by-day increase of the Silverlight market share. The current statistics are that 55.01% browsers worldwide have Silverlight installed. This value is still lower compared to Sun Java (73.01%) and Adobe Flash (96.99%). However, Microsoft is catching up really fast. It seems the competitors act before the Flash values are reached.

Silverlight is running on different browsers (IE 6 to 8, Firefox, SeaMonkey (what’s this?), Safari, Opera, Google Chrome), on different platforms (Windows, Mac), Linux and FreeBSD are covered by Moonlight

More and more features are coming, and the development pace is really fast. Silverlight 4 includes support for printing, multi-touch, access the file system, interop with Office, COM automation, multicast networking…   On devices, Silverlight is also available on Symbian and Windows Phone. All the best qualifications to get more and more market share.

This is where Adobe, Oracle, Google, and Apple come into play. Adobe and Oracle are afraid in losing market share with Sun Java and Adobe Flash and thus ask the EU for help to restrict Microsoft’s success on Silverlight. Google and Apple are not direct competitors in that area, but are also afraid in losing market share with their mobile phones. There are different options for the plan against Silverlight that are proposed.

  • Microsoft must install Adobe Flash and Sun Java as well when a user selects to install Silverlight
  • Silverlight may only be installed on Microsoft platforms

Of course it is either the first or the second option that might be requested.

The first option is in part similar to the ballot screens that’s now offered by Windows Update. However, it is not possible to do exact the same with Silverlight. If a Web page requires Silverlight, the user cannot install Adobe Flash or Sun Java to display this Web page. So all of these addins must be installed instead.

The second option does not require Microsoft to install the competitors technologies along with Silverlight. Contrary, Silverlight might not be installed on non-Microsoft platforms. If it should be allowed to run Silverlight within other browsers on Microsoft’s platform is currently unclear. Google and Apple prefer the second option in the case against Microsoft.

At that time it’s not clear if the competitors succeed with this new case against Microsoft. Nisbum was not successful when demanding the removal of the calculator from Windows in the year 2004. However, many politicians are already discussing different options against Silverlight although I’m unsure if they know what Silverlight is.


Update: this was one of my 1-April posts. Hope you enjoyed it and hopefully it never happens

Microsoft must guarantee safety of browsers offered by Windows Update

Now as Microsoft offers a browser ballot to allow easily installing different browsers (Safari, Firefox, Google Chrome, Opera, IE, and seven more) Microsoft could get into different issues because of this. This ballot was an agreement with the EU because users were not able to install the browser of choice on their system. Microsoft’s initial plan to offer Windows without any browsers was rejected by the EU because most users would not be able to install any browser on their system in that case.

This ballot is in place since 1 month. Now Microsoft could be charged a fine by the EU because of this ballot. The problem is – what if a security leak is found in any of these browsers offered by the ballot? If a user downloads the Firefox browser from the Firefox Web page, or the Opera browser from the Opera Web page, that’s different. In that case the user explicitly navigates to the vendors Web page. However, the browsers are offered by Windows Update. So Microsoft gets some responsibility to update all security leaks in these browsers in the same pace as they are fixed with IE. If a leak is found, the requirement is that Microsoft fixes the leak and delivers a patch through Windows Update. If the leak if not fixed in the same or a shorter time frame than leaks are found and fixed in IE, cases could be opened against Microsoft. Microsoft could be charged the money that was lost because of security issues. Because the loss of money in regard to security issues usually is hard to evaluate, the EU considers defining a standard fine per day a fix is not delivered.

How bad is this? I thought that the ballot was already too much as I don’t think users are not able to download and install a browser of their choice to the system. And IE didn’t have 95% installed base in Europe before the ballot. Now Microsoft could be charged a fine for software errors from other vendors?


Update: this was one of my 1-April posts. Hope you enjoyed it!