How to use Windows Runtime classes in .NET Core libraries?

With .NET Core 3 and up (now in preview) there is a package you can install that includes most WinRT classes Microsoft.Windows.SDK.Contracts


Finally solved the problem on my own! (If you're looking for a quick answer, you may want to scroll down.)

I remembered by chance that the .NET Core GitHub repo had a bunch of WinRT-specific libraries, like System.Runtime.WindowsRuntime. So, I headed over there to see how they did it.

It appears they use some kind of internally-hosted "targeting pack", which contains a single Windows.winmd file (which holds all the types in the Windows Runtime), to achieve this affect. Unfortunately, the package is hosted on a private NuGet feed meant only for the .NET Core team, so I can't use it.

I've opened an issue about this on the CoreFX repo here, so I can petition Microsoft for an official solution to this problem. In the meantime, I've taken matters into my own hands. I've found all the different versions of Windows.winmd on my laptop, and uploaded them as NuGet packages. Here they are:

  • Target.Windows
  • Target.WindowsPhone
  • Target.WindowsRuntime

You can use them like this:

"frameworks": {
    ".NETPortable,Version=v4.5,Profile=Profile32": {
        "dependencies": {
            "Target.WindowsRuntime": "8.1.2"
        }
    }
}

After that, you'll be able to write something like this:

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class MyApp : Application
{
    public MyApp()
    {
        var button = new Button();
        button.Content = "Hello, world!";
    }
}

and it'll just work.