[ 本文适用于编写 Windows 运行时应用的 Windows 8.x 和 Windows Phone 8.x 开发人员。如果你要针对 Windows 10 进行开发,请参阅 最新文档 ]
本主题介绍如何显示设备图标。
你需要了解的内容
技术
- 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;
}
}
注意 或者,你可以将对 getThumbnailAsync 的调用替换为对 getGlyphThumbnailAsync 的调用,以获取设备的字形。
步骤 5: 添加代码以枚举设备
- 将代码添加到你的 Default.js 文件,该文件枚举你希望显示其图标的设备。
- 将设备的 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 来为设备获取字形。