빠른 시작: 널리 사용되는 장치 열거(HTML)

[ 이 문서는 Windows 런타임 앱을 작성하는 Windows에서 8.x 및 Windows Phone 8.x 개발자를 대상으로 합니다. Windows 10용으로 개발하는 경우에는 최신 설명서를 참조하세요.]

Windows.Devices.Enumeration 네임스페이스에서는 장치를 열거하기 위한 두 가지 메서드 FindAllAsyncCreateWatcher를 제공합니다. FindAllAsync는 사용 가능한 장치에 대한 일회성 검색을 수행하며 사용자가 장치를 추가, 삭제 또는 변경할 경우 업데이트가 필요하지 않은 앱에 가장 적합합니다. 운영 체제에서 초기 열거를 완료한 후 사용자가 장치를 추가, 삭제 또는 변경할 경우 CreateWatcher는 장치를 열거하고 알림 이벤트도 만듭니다. 여기서는 FindAllAsync를 사용하여 일반적으로 사용되는 장치의 일회성 열거를 수행하는 방법을 보여 줍니다.

목표: Windows.Devices.Enumeration 네임스페이스를 사용하여 일반 장치 범주에서 사용 가능한 장치를 나열합니다.

사전 요구 사항

개발자가 JavaScript 및 HTML에 익숙하다고 가정합니다.

완료 시간: 20 분.

지침

1. Microsoft Visual Studio 열기

Visual Studio의 인스턴스를 엽니다.

2. 새 프로젝트 만들기

새 프로젝트 대화 상자의 JavaScript 프로젝트 유형에서 새 앱을 선택합니다.

3. 앱 HTML 삽입

Default.html을 열고 다음 코드를 파일에 복사하여 파일의 내용을 대체합니다.

이 HTML은 사용자가 열거할 7가지 장치 유형(마이크, 오디오 재생, 웹캠, 이동식 저장소, MTP 장치 서비스, SMS 장치 및 근접 연결 장치)에서 선택할 수 있는 사용자 인터페이스를 제공합니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script src="/js/default.js"></script>
</head>
<body data-design-activate="defaultPage.activated">
    <h1>Device Enumeration Sample</h1>

    <h2 >Input</h2>

    <div>            

        <div id="Input">
           <p>This scenario demonstrates using the device enumeration API
              to look for specific device interfaces. A device interface
              is the programmatic entry point for a device.</p>
           <p>Select a device interface class</p>
                <select id="SelectInterfaceClass" size="7" >
                    <option value="audioCapture">Audio Capture</option>
                    <option value="audioRender">Audio Playback</option>
                    <option value="videoCapture">Webcams</option>
                    <option value="portableStorageDevice">Portable Storage</option>
                    <option value="mtpService">MTP Device Service</option>
                    <option value="sms">SMS Device</option>
                    <option value="proximity">Proxmity Device</option>
                </select>
                <br />
                <p>Clicking the enumerate button will start a search for 
                 device interfaces that belong to the specified device interface class. 
                 The device interfaces will be listed below.</p>
          <input onclick="onEnumerateDeviceInterfaces()" type="button" value="Enumerate" />
                <br /><br />
            </div>
    </div>


    <h2> Output</h2>

            <div id="statusMessage"></div>

            <!-- Device Enumeration results are displayed in this element -->
            <div  id="Output"></div>
</body>
</html>

4. 앱 JavaScript 삽입

Default.js 파일을 열고 다음 코드를 삽입합니다.

사용자가 선택한 장치 유형에 따라 onEnumerateDeviceInterface 함수는 DeviceClass 값을 선택하거나 getDeviceSelector 함수에서 선택기 문자열을 가져옵니다. 그런 다음 앱은 이 값을 FindAllAsync에 전달합니다. 열거에 성공하면 successCallback 함수가 장치 정보를 출력하고 열거에 실패하면 errorCallback 함수가 오류 메시지를 출력합니다.

function onEnumerateDeviceInterfaces() {
    document.getElementById("Output").innerHTML = ""; // clear output
    try {
        var selection = document.getElementById("SelectInterfaceClass");
        var selectedDeviceClass = 
            selection.options[selection.selectedIndex].value;
        var deviceClass;
        var Enumeration = Windows.Devices.Enumeration;
        var selectorString = "";

        var mtpServiceDevice = Windows.Devices.Portable.ServiceDevice;
        var smsDevice = Windows.Devices.Sms.SmsDevice;
        var proximityDevice = Windows.Networking.Proximity.ProximityDevice;
        switch (selectedDeviceClass) {
            case "audioCapture":
                // same as:
                // var mediaDevice = Windows.Media.Devices.MediaDevice;
                // selectorString =  mediaDevice.getAudioCaptureSelector();
                deviceClass = Enumeration.DeviceClass.audioCapture;
                break;
            case "audioRender":
                // same as:
                // var mediaDevice = Windows.Media.Devices.MediaDevice;
                // selectorString =  mediaDevice.getAudioRenderSelector();
                deviceClass = Enumeration.DeviceClass.audioRender;
                break;
            case "portableStorageDevice":
                // same as: 
                // var storageDevice = Windows.Devices.Portable.StorageDevice;
                // selectorString = storageDevice.getDeviceSelector();
                deviceClass = Enumeration.DeviceClass.portableStorageDevice;
                break;
            case "videoCapture":
                // same as:
                // var mediaDevice = Windows.Media.Devices.MediaDevice;
                // selectorString =  mediaDevice.getVideoCaptureSelector();
                deviceClass = Enumeration.DeviceClass.videoCapture;
                break;
            case "mtpService":
            // Windows.Devices.Portable.ServiceDevice.getDeviceSelector
                selectorString = mtpServiceDevice.getDeviceSelector(Windows.Devices.Portable.ServiceDeviceType.calendarService);
                break;
            case "sms":
            // Windows.Devices.Sms.SmsDevice.getDeviceSelector
                selectorString = smsDevice.getDeviceSelector();
                break;
            case "proximity":
            // Windows.Networking.Proximity.ProximityDevice.getDeviceSelector
                selectorString = proximityDevice.getDeviceSelector();
                break;
            case "imageScanner":
            // same as:
            // var scannerDevice = Windows.Devices.Scanners.ImageScanner;
            // selectorString = scannerDevice.getDeviceSelector();
                deviceClass = Enumeration.DeviceClass.imageScanner;
                break;
            default: deviceClass = Enumeration.DeviceClass.all;
        }

        var DeviceInformation = Enumeration.DeviceInformation;
        if (selectorString == "") {
            DeviceInformation.findAllAsync(deviceClass).then(
                successCallback, 
                errorCallback
            );
        } else {
            DeviceInformation.findAllAsync(selectorString, null).then(
                successCallback, 
                errorCallback
            );
        }
    } catch (e) {
        document.getElementById("statusMessage").innerHTML = 
            "Failed to enumerate devices, error: " + e.message;
    }
}

// Handles successful completion of the findAllAsync method.
function successCallback(deviceInformationCollection) {
    var numDevices = deviceInformationCollection.length;
    document.getElementById("statusMessage").innerHTML = 
        numDevices + " device interface(s) found";
    if (numDevices) {
        for (var i = 0; i < numDevices; i++) {
            printFriendlyNameAndID(deviceInformationCollection[i], 
                document.getElementById("Output"));
        }
    } else {
        document.getElementById("statusMessage").innerHTML = "No devices found";
    }
}

// Handles an error completion of the findAllAsync method.
function errorCallback(e) {
    document.getElementById("statusMessage").innerHTML = 
        "Failed to find devices, error: " + e.message;
}

// Prints the friendly name of the device interface and its ID 
// The ID is the device interface path.
function printFriendlyNameAndID(deviceInterface, log) {

    // The name property is equivalent to System.ItemNameDisplay property
    log.innerHTML += "<h3>" + 
            deviceInterface.name + "<h3/>";
    log.innerHTML += "<p>Interface ID: " + deviceInterface.id;    
    log.innerHTML += "<p>Enabled: " + deviceInterface.isEnabled;
    
    log.innerHTML += "<br />";
}

참고  

처음 네 개 선택 항목의 경우 DeviceClass 열거 값을 FindAllAsync에 전달할 수 있습니다. 이는 장치 유형과 관련된 Windows 런타임 API에서 선택기 문자열을 가져오고 선택기를 FindAllAsync에 전달하는 것과 동일합니다. DeviceClass 열거 대신 선택기 문자열을 사용하는 코드는 switch 문의 관련 사례 내에 주석으로 처리되어 있습니다.

마지막 세 개 선택 항목의 경우 DeviceClass 열거 값이 없으므로 적절한 선택기 문자열을 가져오는 API 호출만 표시됩니다.

 

5. 앱 빌드

빌드 메뉴에서 솔루션 빌드를 클릭하여 프로젝트를 빌드합니다.

6. 앱 테스트

  1. 디버그 메뉴에서 디버깅 시작을 클릭하여 솔루션을 테스트합니다.
  2. 열거할 장치 인터페이스 클래스를 선택합니다.
  3. 열거 단추를 클릭하여 지정한 장치 인터페이스 클래스에 속한 장치 인터페이스 검색을 시작합니다. 앱은 만든 페이지의 중간 아래에 장치 인터페이스를 나열합니다.

7. 고유한 장치 기능 추가(옵션)

장치를 나열하기만 하지 않고 장치 기능에 액세스하려면 열거한 장치의 DeviceInformation.id 속성을 장치를 사용하는 Windows 런타임 API에 전달합니다. 예를 들어 열거한 웹캠의 ID로 Windows.Media.Capture.MediaCaptureInitializationSettings.VideoDeviceId 속성을 지정하여 비디오 캡처에 사용할 웹캠을 지정할 수 있습니다.

  1. 필요한 기능을 프로젝트의 package.appxmanifest 파일에 추가합니다.

  2. 먼저 장치와 상호 작용하는 데 사용할 수 있는 API에 장치 ID를 전달합니다. 다음은 장치 ID를 사용하여 장치를 사용하는 개체를 초기화하는 몇 가지 메서드입니다.

    MTP 장치 서비스를 사용하는 WPD 장치(Windows.Devices.Portable.ServiceDevice.GetDeviceSelector 또는 Windows.Devices.Portable.ServiceDevice.GetDeviceSelectorFromServiceId를 사용하여 열거)의 경우 다음과 같이 장치를 사용할 COM 자동화 개체를 만들 수 있습니다.

    deviceFactory = new ActiveXObject("PortableDeviceAutomation.Factory");

    var device = deviceFactory.getDeviceFromId(deviceId);

요약 및 다음 단계

Windows.Device.Enumeration.DeviceClass 열거 값이나 getDeviceSelector 메서드의 선택기 문자열을 findAllAsync에 전달하여 일반적인 장치 유형을 열거하는 방법을 알아보았습니다.

필요한 장치 인터페이스 클래스가 Windows.Device.Enumeration.DeviceClass 열거에 없고 선택기를 가져오는 Windows 런타임 API가 없는 경우 AQS(고급 검색 구문) 문자열을 직접 작성하여 findAllAsync에 전달해야 합니다.

지정된 유형의 사용 가능한 장치에 대한 쿼리를 작성하려면 장치 클래스 GUID를 알고 있어야 합니다. 다음 코드에는 사용자가 입력 상자에 입력한 GUID로 지정된 장치 인터페이스 클래스에 속해 있는 사용 가능한 장치에 대한 쿼리가 포함되어 있습니다. GUID는 "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" 형식이어야 합니다.

참고  GUID는 선택기 문자열 내에서 따옴표로 묶어야 합니다. 예: var selectorString = "System.Devices.InterfaceClassGuid:=\"{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\"";

 

        if (textinput.value != ""){
            var textDeviceInterfaceClassGUID = textinput.value;
            var selectorString = "System.Devices.InterfaceClassGuid:=\"" + 
                textDeviceInterfaceClassGUID + 
                "\" AND System.Devices.InterfaceEnabled:=true";
            var Enum = Windows.Devices.Enumeration;
            Enum.DeviceInformation.findAllAsync(selectorString, null).then(
                    successCallback, 
                    errorCallback
                );

// Handles successful completion of the findAllAsync method.
function successCallback(deviceInformationCollection) {
    // Add your code here for processing the enumerated device collection.
}

// Handles an error completion of the findAllAsync method.
function errorCallback(e) {
    // Add your error-handling code here.
}

참고  이 샘플에서는 일회성 열거를 보여 주지만, 이는 사용자가 장치를 추가, 제거 또는 변경할 때 사용자 인터페이스를 업데이트해야 하는 앱에는 충분하지 않습니다. 다음 항목에서는 CreateWatcher를 사용하여 장치를 열거하고 장치 알림을 표시하는 방법을 보여 줍니다.

 

동적으로 열거하는 방법

관련 항목

열거를 위한 선택기 문자열을 제공하는 Windows 런타임 API

Windows.Media.Devices.MediaDevice.getAudioCaptureSelector

Windows.Media.Devices.MediaDevice.getAudioRenderSelector

Windows.Media.Devices.MediaDevice.getVideoCaptureSelector

Windows.Media.Devices.MediaDevice.getDefaultAudioRenderId

Windows.Media.Devices.MediaDevice.getDefaultAudioCaptureId

Windows.Devices.Portable.StorageDevice.GetDeviceSelector

Windows.Devices.Portable.ServiceDevice.GetDeviceSelector

Windows.Devices.Portable.ServiceDevice.GetDeviceSelectorFromServiceId

Windows.Devices.Sms.SmsDevice.GetDeviceSelector

Windows.Networking.Proximity.ProximityDevice.GetDeviceSelector

선택기 문자열을 작성하기 위한 AQS(고급 검색 구문)

프로그래밍 방식으로 고급 검색 구문 사용