Monday, January 14, 2013

Referencing the Windows Runtime from Desktop Apps

Most people think of the Windows Runtime as being synonymous with the formerly-known-as “Metro” applications, now called Windows Store apps. To add to the confusion, of course, is the fact that the ARM-based version of the Windows OS is branded as Windows RT. Programmers, being lazy, like our abbreviations so the runtime has been adopted by the world at large as WinRT. Did you know you can reference WinRT from desktop applications? It’s possible, but not easy nor straightforward.

There are actually two approaches you can follow if you wish to build a desktop application that references the Windows Runtime. The first, through the IDE, works like this:

First, create your project and target the .NET Framework 4.5 or later. You see what I did there? By using “later” I’m hoping this post will still be relevant next year. Once your project is created, right-click on the project node and select Unload Project. You should get something like this:

01fig02

Now edit the project and add the following tag inside a PropertyGroup element:

targetplatformversion

Reload the project and you’ll now have access to WinRT. If you go to the Add References tab, There will be a new option to add the Core for the Windows Runtime:

01fig03

Be sure this is included. You might feel like you’re good to go, but there’s actually more to it. Trying to reference WinRT components and compiling will result in an error like this:

01fig04

You need to add another reference to System.Runtime.dll – to do this, browse to the folder:

c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades

You know the drill: if you’re on 32-bit, remove the (x86) portion. There you will find any other necessary DLLs you need to build and compile your application. If that seems like a lot of work, it is. You could try an alternative. My colleague Jeffrey Richter shows you how to do it from the command line in Using the Windows Runtime from a Non-Metro application.

You’ll quickly learn that not all APIs are available to desktop applications, and some that are available on the desktop aren’t available to Windows Store apps. If you are in doubt, consult the MSDN documentation for the API in question. You will see what is supported at the bottom under supported client and server:

01fig06

MSDN also provides a comprehensive Windows 8 API List for desktop apps.