How to shutdown a Windows 10 IoT Core device from a UWP app
When dealing with an embedded device, we may have the need to turn it off. The same is true for Windows 10 IoT Core devices: in fact, the DefaultApp and the Device Portal have an option that allows to shutdown or restart the board. So, if we deploy our app, how can we implement this feature?
First of all, we need to add the Windows IoT Extensions for the UWP to our project:
In this way, we have access to the Windows.System.ShutdownManager class, that we can use to manage the shutdown of devices. It exposes two static methods:
- BeginShutdown(ShutdownKind shutdownKind, TimeSpan timeout) start the shutdown within the specified timeout. The first parameter allos to specify whether we actually want to shutdown or restart the device;
- CancelShutdown cancels a shutdown that is already in progress (i.e., the timeout isn’t already expired).
So, for example:
// Shutdowns the device immediately: ShutdownManager.BeginShutdown(ShutdownKind.Shutdown, TimeSpan.FromSeconds(0)); // Restarts the device within 5 seconds: ShutdownManager.BeginShutdown(ShutdownKind.Restart, TimeSpan.FromSeconds(5));
In order for this code to work properly, we need also to give an extra capability to our app. Let’s open the Package.appxmanifest file with the Visual Studio XML Editor and add or update the following values:
<Package
...
xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10"
IgnorableNamespaces="uap mp iot">
<Capabilities>
...
<iot:Capability Name="systemManagement" />
</Capabilities>
</Package>
If we don’t set this capability, we’ll get an UnauthorizedAccessException error when calling ShutdownManager methods.Beg
-
13/12/2016 at 13:57Dew Drop - December 13, 2016 (#2382) - Morning Dew
