DeviceInformation Класс

Определение

Представляет устройство. Этот класс обеспечивает доступ к известным свойствам устройства, а также к дополнительным свойствам, указанным во время перечисления устройств.

public ref class DeviceInformation sealed
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class DeviceInformation final
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class DeviceInformation
Public NotInheritable Class DeviceInformation
Наследование
Object Platform::Object IInspectable DeviceInformation
Атрибуты

Требования к Windows

Семейство устройств
Windows 10 (появилось в 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (появилось в v1.0)

Примеры

В этом примере выполняется добавочное перечисление устройств, их добавление в список при каждом обнаружении устройства, а также обработка удалений и обновлений.

using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media.Imaging;

using Windows.Devices.Enumeration;
using Windows.Devices.Enumeration.Pnp;


// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Application1
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    /// 
    public sealed partial class BlankPage : Page
    {
        public BlankPage()
        {

            this.InitializeComponent();
        }
        Windows.UI.Core.CoreDispatcher dispatcher;
        public static DeviceWatcher watcher = null;
        public static int count = 0;
        public static DeviceInformation[] interfaces = new DeviceInformation[1000];
        public static bool isEnumerationComplete = false;
        public static string StopStatus = null;

        async void WatchDevices(object sender, RoutedEventArgs eventArgs)
        {
            try
            {
                dispatcher = Window.Current.CoreWindow.Dispatcher;
                watcher = DeviceInformation.CreateWatcher();
                // Add event handlers
                watcher.Added += watcher_Added;
                watcher.Removed += watcher_Removed;
                watcher.Updated += watcher_Updated;
                watcher.EnumerationCompleted += watcher_EnumerationCompleted;
                watcher.Stopped += watcher_Stopped;
                watcher.Start();
                OutputText.Text = "Enumeration started.";

            }
            catch (ArgumentException)
            {
                //The ArgumentException gets thrown by FindAllAsync when the GUID isn't formatted properly
                //The only reason we're catching it here is because the user is allowed to enter GUIDs without validation
                //In normal usage of the API, this exception handling probably wouldn't be necessary when using known-good GUIDs 
                OutputText.Text = "Caught ArgumentException. Failed to create watcher.";
            }
        }

        async void StopWatcher(object sender, RoutedEventArgs eventArgs)
        {
            try
            {
                if (watcher.Status == Windows.Devices.Enumeration.DeviceWatcherStatus.Stopped)
                {
                    StopStatus = "The enumeration is already stopped.";
                }
                else
                {
                    watcher.Stop();
                }
            }
            catch (ArgumentException)
            {
                OutputText.Text = "Caught ArgumentException. Failed to stop watcher.";
            }
        }

        async void watcher_Added(DeviceWatcher sender, DeviceInformation deviceInterface)
        {
            interfaces[count] = deviceInterface;
            count += 1;
            if (isEnumerationComplete)
            {
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    DisplayDeviceInterfaceArray();
                });
            }
        }

        async void watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate devUpdate)
        {
            int count2 = 0;
            foreach (DeviceInformation deviceInterface in interfaces)
            {
                if (count2 < count)
                {
                    if (interfaces[count2].Id == devUpdate.Id)
                    {
                        //Update the element.
                        interfaces[count2].Update(devUpdate);
                    }

                }
                count2 += 1;
            }
            await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                OutputText.Text = "Enumeration updated. ";
                DisplayDeviceInterfaceArray();
            });
        }

        async void watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate devUpdate)
        {
            int count2 = 0;
            //Convert interfaces array to a list (IList).
            List<DeviceInformation> interfaceList = new List<DeviceInformation>(interfaces);
            foreach (DeviceInformation deviceInterface in interfaces)
            {
                if (count2 < count)
                {
                    if (interfaces[count2].Id == devUpdate.Id)
                    {
                        //Remove the element.
                        interfaceList.RemoveAt(count2);
                    }

                }
                count2 += 1;
            }
            //Convert the list back to the interfaces array.
            interfaces = interfaceList.ToArray();
            count -= 1;
            await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                OutputText.Text = "Enumeration device was removed. ";
                DisplayDeviceInterfaceArray();
            });
        }

        async void watcher_EnumerationCompleted(DeviceWatcher sender, object args)
        {
            isEnumerationComplete = true;
            await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    OutputText.Text = "Enumeration complete. ";
                    DisplayDeviceInterfaceArray();
                });
        }

        async void watcher_Stopped(DeviceWatcher sender, object args)
        {
            if (watcher.Status == Windows.Devices.Enumeration.DeviceWatcherStatus.Aborted)
            {
                StopStatus = "Enumeration stopped unexpectedly. Click Watch to restart enumeration.";
            }
            else if (watcher.Status == Windows.Devices.Enumeration.DeviceWatcherStatus.Stopped)
            {
                StopStatus = "You requested to stop the enumeration. Click Watch to restart enumeration.";
            }
        }

        async void DisplayDeviceInterfaceArray()
        {
            DeviceInterfacesOutputList.Items.Clear();
            int count2 = 0;
            foreach (DeviceInformation deviceInterface in interfaces)
            {
                if (count2 < count)
                {
                    DisplayDeviceInterface(deviceInterface);
                }
                count2 += 1;
            }
        }

        async void DisplayDeviceInterface(DeviceInformation deviceInterface)
        {
            var id = "Id:" + deviceInterface.Id;
            var name = deviceInterface.Name;
            var isEnabled = "IsEnabled:" + deviceInterface.IsEnabled;


            var item = id + " is \n" + name + " and \n" + isEnabled;

            DeviceInterfacesOutputList.Items.Add(item);
        }
    }
}

Комментарии

Объект DeviceInformation состоит из удостоверения (DeviceInformation.Id), вида (DeviceInformation.Kind) и контейнера свойств (DeviceInformation.Properties). Все другие свойства объекта DeviceInformation являются производными от контейнера свойств Properties. Например, свойство Name является производным от System.ItemNameDisplay.

Успешное завершение FindAllAsync приводит к тому, что объект DeviceInformationCollection содержит объекты DeviceInformation.

Если вызов CreateWatcher завершается успешно, объект DeviceInformation передается в добавленное событие для каждого найденного устройства.

Свойство Name следует использовать только в целях отображения, а не для поиска устройства, так как имя может измениться из-за локализации или назначения пользователем имени.

CreateFromIdAsync создает объект DeviceInformation в случае успешного выполнения.

Класс DeviceInformation предоставляет сведения об устройстве, но, в частности, предоставляет свойства интерфейса устройства, который представляет функциональные возможности, предоставляемые устройством. Многофункционные устройства могут иметь несколько интерфейсов устройств. Физический объект, который пользователь видит как устройство, называется контейнером устройства и имеет такие свойства, как Manufacturer и ModelID. Дополнительные сведения о перечислении устройств и восстановлении свойств см. в разделе Перечисление устройств.

Свойства

EnclosureLocation

Физическое расположение устройства в его корпусе. Например, он может описать расположение веб-камеры внутри ноутбука.

Id

Строка, представляющая удостоверение устройства.

IsDefault

Указывает, является ли это устройство устройством по умолчанию для класса .

IsEnabled

Указывает, включено ли это устройство.

Kind

Возвращает тип DeviceInformation , представленный этим объектом.

Name

Название устройства. Это имя на лучшем языке для приложения.

Pairing

Возвращает сведения о возможностях связывания этого устройства.

Properties

Хранилище свойств, содержащее хорошо известные значения, а также дополнительные свойства, которые можно указать во время перечисления устройств.

Методы

CreateFromIdAsync(String)

Создает объект DeviceInformation на основе идентификатора DeviceInformation .

CreateFromIdAsync(String, IIterable<String>)

Создает объект DeviceInformation на основе идентификатора DeviceInformation и списка дополнительных свойств.

CreateFromIdAsync(String, IIterable<String>, DeviceInformationKind)

Создает объект DeviceInformation на основе идентификатора DeviceInformation , списка дополнительных свойств и параметра DeviceInformationKind .

CreateFromIdAsync(String, IIterable<String>, DeviceInformationKind, IDeviceEnumerationSettings)

Представляет устройство. Этот класс обеспечивает доступ к известным свойствам устройства, а также к дополнительным свойствам, указанным во время перечисления устройств.

CreateWatcher()

Создает DeviceWatcher для всех устройств.

CreateWatcher(DeviceClass)

Создает DeviceWatcher для устройств, соответствующих указанному классу DeviceClass.

CreateWatcher(String)

Создает DeviceWatcher для устройств, соответствующих указанной строке расширенного синтаксиса запросов (AQS).

CreateWatcher(String, IIterable<String>)

Создает DeviceWatcher для устройств, соответствующих указанной строке расширенного синтаксиса запросов (AQS) и указанной коллекции свойств.

CreateWatcher(String, IIterable<String>, DeviceInformationKind)

Создает DeviceWatcher для устройств, соответствующих указанной строке расширенного синтаксиса запросов (AQS), указанной коллекции свойств и типу устройств.

CreateWatcher(String, IIterable<String>, DeviceInformationKind, IDeviceEnumerationSettings)

Представляет устройство. Этот класс обеспечивает доступ к известным свойствам устройства, а также к дополнительным свойствам, указанным во время перечисления устройств.

FindAllAsync()

Перечисляет все объекты DeviceInformation .

FindAllAsync(DeviceClass)

Перечисляет объекты DeviceInformation указанного класса.

FindAllAsync(String)

Перечисляет объекты DeviceInformation , соответствующие указанной строке селектора интерфейса устройства Расширенного синтаксиса запросов (AQS).

FindAllAsync(String, IIterable<String>)

Перечисляет объекты DeviceInformation , соответствующие указанной строке селектора интерфейса устройства расширенного синтаксиса запросов (AQS), включая указанную коллекцию свойств.

FindAllAsync(String, IIterable<String>, DeviceInformationKind)

Перечисляет объекты DeviceInformation , соответствующие указанной строке селектора интерфейса устройства Расширенного синтаксиса запросов (AQS), типу устройства и включая указанную коллекцию свойств.

FindAllAsync(String, IIterable<String>, DeviceInformationKind, IDeviceEnumerationSettings)

Представляет устройство. Этот класс обеспечивает доступ к известным свойствам устройства, а также к дополнительным свойствам, указанным во время перечисления устройств.

GetAqsFilterFromDeviceClass(DeviceClass)

Создает фильтр, используемый для перечисления через подмножество типов устройств.

GetGlyphThumbnailAsync()

Возвращает глиф для устройства.

GetThumbnailAsync()

Возвращает эскиз для устройства.

Update(DeviceInformationUpdate)

Обновления свойства существующего объекта DeviceInformation.

Применяется к

См. также раздел