如何在添加、删除或更改设备时获得通知 (HTML)

[ 本文适用于编写 Windows 运行时应用的 Windows 8.x 和 Windows Phone 8.x 开发人员。如果你要针对 Windows 10 进行开发,请参阅 最新文档 ]

本教程展示如何以动态方式枚举设备。然后,如果添加或移除设备,或者如果设备属性发生变化,你的应用可以收到通知。

你可以使用 DeviceWatcher 类启动设备枚举。对于找到的每个设备,DeviceWatcher 会引发一个 Add 事件,直到找到所有设备且枚举完成为止。在初始枚举完成之后,如果添加、更新或移除设备,那么 DeviceWatcher 会继续引发事件。

你需要了解的内容

技术

  • Windows Runtime

先决条件

JavaScript 和 HTML。

说明

步骤 1: 打开 Microsoft Visual Studio

打开 Visual Studio 的一个实例。

步骤 2: 创建新项目

在“新建项目”对话框中,从“JavaScript”>“Windows 应用商店应用”****项目类型中,选取一个空白应用。

步骤 3: 插入应用程序 JavaScript 和 HTML

打开你的 Default.html 并将此 HTML 复制到其中,以替换原来的内容。

<!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>

步骤 4:

将此代码粘贴到 default.js 中,替换该文件的内容。

    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);
        }
    }

备注

此示例以递增方式枚举设备。它在每次找到设备时将设备添加到列表中,同时查看是否存在更新。枚举完成之后,该应用会立即输出一个设备列表。如果用户在初始枚举完成之后添加、更新或移除设备,那么该应用还会输出一条消息。

注意  当添加、移除或更新设备时,应用必须订阅所有 addedremovedupdated 事件才能收到通知。如果应用仅处理 added 事件,则在初始设备枚举完成后,如果将设备添加到系统,则不会收到更新。