Share via


Using Windows Universal Runtime APIs from a standard Unity executable - Go deeper

Let's use and continue the work done in the previous article Using Windows Universal Runtime APIs from a standard Unity executable. The context was: We are developing a game or an app using Unity and we build directly an executable (not an UWP application). How can we use the UWP APIs? I gave an answer which was:

  1. We create a C# .NET dll that calls the UWP APIs.
  2. We use the compiled dll as a Unity Plugin and we build the Unity project as a standard Windows executable.
  3. We package the executable with Desktop Bridge

The sample code provided on GitHub allows us to create Toast notification. We add today the possibllity to use Live Tiles and scheduled toast notifications.

👨‍💻 Modify the C# .NET dll to use others UWP APIs

C# code for Live tiles

So for the code modification inside the C# .NET dll project. You can do what you are used to do inside classic dll project on Windows. The only pre-requisite is to preced the method with a 'DllExport' in order to make this method visible from the Unity script:

 [DllExport(CallingConvention.StdCall)]

Here is a sample code to modify the square tile and make it live:

 class LiveTileHelper
{
    [DllExport(CallingConvention.StdCall)]
    public static string UpdatePrimaryTile(string text, int durationSeconds = 10)
    {
        var template = Windows.UI.Notifications.TileTemplateType.TileSquare150x150Block;
        var tileXml = Windows.UI.Notifications.TileUpdateManager.GetTemplateContent(template);

        var tileTextAttributes = tileXml.GetElementsByTagName("text");
        tileTextAttributes[0].AppendChild(tileXml.CreateTextNode(text));

        var tileNotification = new Windows.UI.Notifications.TileNotification(tileXml);

        tileNotification.ExpirationTime = DateTime.Now.AddSeconds(durationSeconds);
        Windows.UI.Notifications.TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
        return "Ok";
    }
}

C# code for scheduled toast notifications

The same rul applies here (DllExport). Here is a sample code to schedule a toast for a later display by windows:

 private static ScheduledToastNotification CreateAScheduleToast(
            string toastTitle,
            string toastContent,
            DateTime scheduleTime)
{

    var doc = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

    var strings = doc.GetElementsByTagName("text");
    strings[0].AppendChild(doc.CreateTextNode(toastTitle));
    strings[1].AppendChild(doc.CreateTextNode("Scheduled: " + toastContent));

    var toast = new ScheduledToastNotification(doc, scheduleTime);
    return toast;
}

[DllExport(CallingConvention.StdCall)]
public static string NotifyWithDelay(string toastTitle, string toastContent, int delayinMilliseconds)
{
    try
    {
        var scheduleTime = DateTime.Now.AddMilliseconds(delayinMilliseconds);
        ScheduledToastNotification toast = CreateAScheduleToast(toastTitle, toastContent, scheduleTime);

        // Add to the schedule.
        ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
    }
    catch (AggregateException ex)
    {
        return "Exception:" + ex.ToString() + " exMessage:" + ex.Message;
    }
    return "Ok";
}

Compile the C# .NET dll

The last steps on the dll project is to compile using RELEASE and x64. Visual Studio compiles in X64 in RELEASE

Note the output folder of the dll because you will have to copy it to the Unity project's folder. Generally it is something like \bin\x64\Release.

🎮 Modify the Unity app to use the updated .NET dll

Copy the new C# .NET to the Unity project

The first step is to update the C# .NET dll already in the \Assets\Plugins folder of the Unity project. To do this, just copy/paste the dll from the C# .NET dll project ( \bin\x64\Release) to the Plugins folder of the Unity project ( \bin\x64\Release).

Please refer to the previous article for the full steps.

Update the Unity script to call the new method

In order to inform Unity about the new methods available you just have to do a kind of 'copy/paste' of the method declarations with DllImport and extern static before. Especially if you use simple types for parameters. Here are examples:

 [DllImport("dotNETClassLibraryUsingUWPAPIs")]
extern static string NotifyWithDelay(string toastTitle, string toastContent, int delayinMilliseconds);

[DllImport("dotNETClassLibraryUsingUWPAPIs")]
extern static string UpdatePrimaryTile(string text, int durationSeconds);

And you are done! To call the method, just use them in the script:

 void Update()
{
    if (Input.GetKeyDown(KeyCode.S))
    {
        string output = NotifyWithDelay("Schedule Toast title",
            "Unity toast sent at " + System.DateTime.Now.ToLongTimeString(), 5000);
    }

    if (Input.GetKeyDown(KeyCode.T))
    {
        string output = UpdatePrimaryTile("Updated at " 
            + System.DateTime.Now.ToLongTimeString(), 20);
    }
}

📥 Last step: package the app using Desktop Bridge

The Unity app is compiled as a standard executable. We package it using the tool called Desktop App Converter:

  • Launch it as an Administrator

App Desktop Converter Launched in Admin

  • Create an empty folder for getting the upcoming package. Exemple: C:\Temp\UnityExeAppPackage

  • Use the following command line with the path to the folder containing the compiled UnityEXEApp.exe and the empty folder just created for the output:

    DesktopAppConverter.exe -Installer "C:\UWPAPIsUsedFromUnityEXEApp\UnityEXEApp\Builds" -AppExecutable "UnityEXEApp.exe" -Destination "C:\Temp\UnityExeAppPackage" -PackageName "UnityEXEApp" -Publisher "CN=sbovo" -Version "1.1.0.0" -MakeAppx -Sign -Verbose

To test the app, you have to first install the auto-generated.cer certificate in the Trusted People container for local machine certificates.

Again, the full steps are described in the previous article.

Here is the result in action!

Live tiles Live tiles displayed in the Windows Start menu

Scheduled Toast A Toast appears in the screen

Conclusion

Using a C# .NET dll project and exporting methods is a great and easy way to provide UWP APIs access to apps that are not UWP native apps. Take some time to create you C# .NET dll project with all "piping" and you will able to use lots of UWP Sample code!

As always, all source code is in GitHub - https://github.com/Microsoft/Windows-AppConsult-Samples-DesktopBridge/tree/master/UWPAPIsUsedFromUnityEXEApp

Bye,

@sbovo for the 💻 🎮 Windows AppConsult team.