Skip to content

Using Windows Runtime in a .NET desktop application

jbe2277 edited this page Sep 5, 2015 · 8 revisions

.NET desktop applications can leverage of the new Windows Runtime API when they run on a Windows 8 or newer. The Windows API reference for Windows Runtime apps show which API can be used within a desktop application (see Requirements section).

Minimum supported client    Windows 8 [Windows Store apps, desktop apps]

Enabling this support must be done by editing the Visual Studio project file. Select the project in the Visual Studio Solution Explorer and select in the context menu Unload project. After unloading the project use the context menu again for Edit MyProject.csproj. Add the TargetPlatformVersion node to the file:

  <FileAlignment>512</FileAlignment>
  <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
  <WarningLevel>4</WarningLevel>
  <TargetPlatformVersion>8.1</TargetPlatformVersion>
</PropertyGroup>

Now reload the project and add a reference. In the dialog select the category “Windows” and select “Windows” in the list. A second reference is required for the mapping of Windows Runtime types to .NET types. Open the “Reference” dialog a second time and add the following assembly via Browse:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll

Unfortunately, this assembly reference is added by the relative path location. If the solution is moved into another folder structure or if team colleagues are mapping the source control folders in other folders than this referenced assembly might not be found by the build system. A workaround is to use an MSBuild variable in the project file. Unload the project and edit the project file again. Search for the assembly reference:

<Reference Include="System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll</HintPath>
</Reference>

Replace the hint path with the following line:

<HintPath>$(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll</HintPath>

That is all. The Windows Runtime can be used now in the .NET project. Here is a little example to test if the Windows Runtime integration was successful:

var folder = await StorageFolder.GetFolderFromPathAsync(@"C:\Users");
Console.WriteLine(folder.DisplayName);

Note: The examples above are targeting Windows 8.1. If you need to support Windows 8.0 as well then replace the TargetPlatformVersion with the version 8.0.

Further readings

  1. MSDN Blog: Using Windows 8 WinRT APIs in .NET Desktop Applications
  2. Windows API reference for Windows Runtime apps