Share via


如何顯示裝置圖示 (HTML)

[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]

這個主題說明如何顯示裝置圖示。

您必須知道的事

技術

  • Windows Runtime

先決條件

  • 您應該熟悉 HTML 和 JavaScript。

指示

步驟 1: 開啟 Microsoft Visual Studio

開啟 Visual Studio 的執行個體。

步驟 2: 建立新專案

在 [新增專案] 對話方塊中,從 [JavaScript]**** > [Windows 市集應用程式] 專案類型按一下 [空白的應用程式]****。

步驟 3: 插入 HTML

開啟 Default.html,並以這個程式碼取代檔案內容。

<!DOCTYPE html>
<html>
<head>
    <title>Display the Device Icon</title>
    <script type="text/javascript" src="/js/default.js"> </script>
</head>
<body>

    <h1>Device Icon</h1>

    <div id="statusMessage"></div>
    // The size of the returned icon is 256 X 256.
    <img id="deviceImage"/>

</body>
</html>

步驟 4: 插入顯示圖示的函式

開啟 Default.js,並以下列程式碼取代內容。


// Takes a parameter of type DeviceInformation
// and retrieves a DeviceThumbnail to pass to displayImage().
function getImage (device) {   

    var thumbnail = null;
    if (device){
        device.getThumbnailAsync().then(
            function (thumbnail) {
            // A valid thumbnail is always returned.
                displayImage(thumbnail);
            });
    }                                                                                     
}

function displayImage(imageFile) {
   
    try {
        // Setting 2nd parameter to 'false' cleans up 
        // the URL after first use.
        // We set this because we only need to load the URL
        // into the image tag once.
        document.getElementById("deviceImage").src = 
            window.URL.createObjectURL(imageFile, false);
    } catch (e) {
        document.getElementById("statusMessage").innerHTML = 
            "Could not display image, error: " + e.message;
    }
                
}

注意  您也可以使用 getGlyphThumbnailAsync 呼叫來取代 getThumbnailAsync 呼叫,藉此取得裝置的圖像。

 

步驟 5: 新增程式碼以列舉裝置

  1. 新增程式碼到您的 Default.js 檔案以列舉您要顯示其圖示的裝置。
  2. 將裝置的 DeviceInformation 物件傳送到您定義的 getImage() 函式。

而可顯示圖示的裝置將取決於您的系統。這個程式碼會找到第一個相機 (如果有的話),然後顯示它的影像。


(function() {
    var Enum = Windows.Devices.Enumeration;
    Enum.DeviceInformation.findAllAsync(
        Enum.DeviceClass.videoCapture).then(
                    successCallback 
            );
})();

function successCallback(deviceInformationCollection) {
    var numDevices = deviceInformationCollection.length;
    if (numDevices) {
        getImage(deviceInformationCollection[0]);
    } else {
        document.getElementById("statusMessage").innerHTML =
            "No devices found.";
    }
}

備註

傳回的圖示大小是 256 x 256 像素。

使用 getThumbnailAsync 取得裝置的寫實圖示。使用 getGlyphThumbnailAsync 取得裝置的圖像。