How to get notifications if devices are added, removed, or changed (HTML)

This tutorial shows you how to enumerate devices dynamically. Then, your app can receive notification if devices are added or removed, or if device properties change.

You use the DeviceWatcher class to start a device enumeration. For each device that's found, DeviceWatcher raises an Add event until all devices are found and the enumeration is complete. After the initial enumeration is complete, DeviceWatcher continues to raise events if a device is added, updated, or removed.

What you need to know

Technologies

  • Windows Runtime

Prerequisites

JavaScript and HTML.

Instructions

Step 1: Open Microsoft Visual Studio

Open an instance of Microsoft Visual Studio.

Step 2: Create a new project

In the New Project dialog box, from the JavaScript > Windows Store apps project types, pick a blank app.

Step 3: Insert the Application JavaScript and HTML

Open your Default.html and copy this HTML into it, replacing its original contents.

<!DOCTYPE html>
<html>
<head>
  <title>Device Enumeration Sample</title>
  <meta charset="utf-8" />
  <script src="/js/default.js"></script>
</head>
<body role="application">
    <h1>Device Enumeration Sample</h1>
    <h2 >Input</h2>
    <div >            
            <div >
            <p>This example incrementally enumerates devices, adding them to a list each time a device is found, and also watching for updates.
               Once enumeration is complete, the list of devices is printed.</p> 
                <input type="button" value="Watch(All Devices)" onclick="WatchDevices()"/>
                <br /><br />

                <input type="button" value="Stop" onclick="stopWatcher()"/>
                <br /><br />
            </div>
    </div>

    <h2 > Output</h2>
            <div id="statusMessage"></div>
            <!--  Output -->
            <div  id="output"></div>
</body>
</html>

Step 4:

Paste this code into default.js, replacing the contents of the file.

    var watcher;
    var isEnumerationComplete = false;
    var deviceArray = new Array(); // Saves the enumeration results

    function WatchDevices() {
        try {
            output.innerHTML = ""; // clear output field

            watcher = 
                Windows.Devices.Enumeration.DeviceInformation.createWatcher();
            // Add event handlers
            watcher.addEventListener("added", onAdded);
            watcher.addEventListener("removed", onRemoved);
            watcher.addEventListener("updated", onUpdated);
            watcher.addEventListener("enumerationcompleted", 
                onEnumerationCompleted);
            watcher.addEventListener("stopped", onStopped);
            // Start enumerating and listening for events
            watcher.start();
        } catch (e) {
            document.getElementById("statusMessage").innerHTML = 
                "Failed to create watcher, error: " + e.message;
        }
    }

    function stopWatcher() {
        try {
            watcher.stop();
        }
        catch (e) {
            document.getElementById("statusMessage").innerHTML = 
                "Failed to stop watcher: " + e.message;
        }
    }

    function onAdded(devinfo) {
        document.getElementById("output").innerHTML += "<p>Device added: " + 
            devinfo.name + "</p>";
        deviceArray.push(devinfo);
        if (isEnumerationComplete) {
            output.innerHTML = ""; // clear output field
            printDeviceArray(document.getElementById("output"));
        }
        
    }

    function onUpdated(devUpdate) {
        document.getElementById("output").innerHTML += "<p>Device updated.</p>";
        for (var i = 0; i < deviceArray.length; i++) {
            if (deviceArray[i].id == devUpdate.id) {
                deviceArray[i].update(devUpdate);
            }
        }
        output.innerHTML = ""; // clear output field
        printDeviceArray(document.getElementById("output"));
    }

    function onRemoved(devupdate) {
        document.getElementById("output").innerHTML += "<p>Device removed.</p>";
        for (var i = 0; i < deviceArray.length; i++) {
            if (deviceArray[i].id == devupdate.id) {
                deviceArray[i].slice(devupdate);
            }
        }
        output.innerHTML = ""; // clear output field
        printDeviceArray(document.getElementById("output"));
    }

    function onEnumerationCompleted(obj) {
        isEnumerationComplete = true;
        document.getElementById("output").innerHTML += 
            "<p>Enumeration Completed.</p>";
        printDeviceArray(document.getElementById("output"));
    }

    function onStopped(obj) {
        document.getElementById("output").innerHTML += "<p>Stopped.</p>";
        if (watcher.status == Windows.Devices.Enumeration.DeviceWatcherStatus.aborted) {
           document.getElementById("output").innerHTML += 
            "<p>Enumeration stopped unexpectedly. </p>";
           document.getElementById("output").innerHTML += 
            "<p>Click the Watch button to restart enumeration.</p>";
        } else if (watcher.status == Windows.Devices.Enumeration.DeviceWatcherStatus.stopped) {
           document.getElementById("output").innerHTML += 
            "<p>You requested to stop enumeration. </p>";
           document.getElementById("output").innerHTML += 
            "<p>Click the Watch button to restart enumeration.</p>";
        }

    }


    // Prints the friendly name of the device interface, 
    // its ID (device interface path), and whether it is enabled.
    function printDevice(deviceInterface, outputDestination) {
        outputDestination.innerHTML += "<p>Name: " + 
            deviceInterface.name + "<p/>"; 
        outputDestination.innerHTML += "<p>Interface ID: " + 
            deviceInterface.id + "<p/>";    
        outputDestination.innerHTML += "<p>Enabled: " + 
            deviceInterface.isEnabled + "<p/>";
        outputDestination.innerHTML += "<br />";
    }

    function printDeviceArray(outputDestination) {
        for (var i = 0; i < deviceArray.length; i++) {
            printDevice(deviceArray[i], outputDestination);
        }
    }

Remarks

This example incrementally enumerates devices. It adds them to a list each time a device is found, and also watches for updates. Adter enumeration is complete, the app prints a list of devices. The app also prints a message if a user adds, updates, or removes devices after the initial enumeration completes.

Note  An app must subscribe to all of the added, removed, and updated events to be notified when there are device additions, removals or updates. If an app handles only the added event, it will not receive an update if a device is added to the system after the initial device enumeration completes.