我正在制作与USB相关的节目。
我正在测试MS官方示例,但当我断开USB设备时, DeviceWatcher.Removed事件可以被称为,只是被称为DeviceWatcher.Updated
我通过My Mobile Phone和USB UART Device测试DeviceWatcher。
代码在这里。我在MSDN的某个地方找到了代码。 (我修改了一点。)
namespace USBTest
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
///
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
Windows.UI.Core.CoreDispatcher dispatcher;
public static DeviceWatcher watcher = null;
public static int count = 0;
public static DeviceInformation[] interfaces = new DeviceInformation[65535];
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);
}
}
}
<Page
x:Class="USBTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:USBTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid x:Name="ContentRoot" Margin="100,20,100,20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Header -->
<StackPanel x:Name="Header" Grid.Row="0">
<StackPanel Orientation="Horizontal"/>
</StackPanel>
<!-- Content -->
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Grid.Row="1" ZoomMode="Disabled">
<StackPanel x:Name="ContentPanel">
<TextBlock Text="Device Enumeration Sample" Margin="0,25,0,20" Height="25" />
<StackPanel x:Name="InputPanel" Orientation="Horizontal" HorizontalAlignment="Left" Height="266">
<StackPanel/>
<StackPanel x:Name="Description" MaxWidth="900">
<!-- Enumerate Device Interfaces -->
<StackPanel x:Name="EnumerateDevicesInput" Height="270" Width="857">
<TextBlock Text="Input" Margin="0,25,0,20" />
<TextBlock TextWrapping="Wrap" Text="This example app incrementally enumerates devices, adding them to a list each time a device is found, and also watching for updates. After enumeration is complete, the app prints the list of devices. The app reprints the list if devices are updated, removed, or added." HorizontalAlignment="Left"/>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0"/>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0"/>
<Button Name="WatchAllDevices" Content="Watch (All devices)" Margin="0,10,10,0" Click="WatchDevices" />
<Button Name="StopAllWatcher" Content="Stop" Margin="0,10,10,0" Click="StopWatcher" />
</StackPanel>
</StackPanel>
</StackPanel>
<TextBlock Text="Output" Margin="0,25,0,20" />
<!-- Output section -->
<StackPanel x:Name="Output" HorizontalAlignment="Left">
<TextBlock Name="OutputText" />
<!-- Device Interfaces-->
<ListBox Name="DeviceInterfacesOutputList" IsEnabled="False" BorderThickness="0" />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Grid>
</Page>