我尝试处理 MediaDevice::DefaultAudioRenderDeviceChanged 和 Windows::Devices::Enumeration::DeviceWatcher。但它们都不能按预期工作。
您可以使用DeviceWatcher 来处理DeviceWatcher.Added 或DeviceWatcher.Removed 事件。
MainPage.xaml.cpp:
using namespace Windows::Devices::Enumeration;
using namespace Windows::UI::Core;
MainPage::MainPage()
{
InitializeComponent();
}
void DeviceWatcherCppSample::MainPage::btnClick_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
watcher=DeviceInformation::CreateWatcher(DeviceClass::AudioRender);
handlerAddedToken=watcher->Added += ref new Windows::Foundation::TypedEventHandler<DeviceWatcher ^, DeviceInformation ^>(this, &DeviceWatcherCppSample::MainPage::OnAdded);
handlerRemovedToken= watcher->Removed += ref new Windows::Foundation::TypedEventHandler<DeviceWatcher ^, DeviceInformationUpdate ^>(this, &DeviceWatcherCppSample::MainPage::OnRemoved);
handlerUpdatedToken= watcher->Updated += ref new Windows::Foundation::TypedEventHandler<Windows::Devices::Enumeration::DeviceWatcher ^, Windows::Devices::Enumeration::DeviceInformationUpdate ^>(this, &DeviceWatcherCppSample::MainPage::OnUpdated);
watcher->Start();
}
void DeviceWatcherCppSample::MainPage::OnAdded(DeviceWatcher ^sender, DeviceInformation ^args)
{
this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]()
{
tbResult->Text = args->Name +"is Added";
}));
}
void DeviceWatcherCppSample::MainPage::OnRemoved(DeviceWatcher ^sender, DeviceInformationUpdate ^args)
{
this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]()
{
tbResult->Text = args->Id + "is Removed";
}));
}
void DeviceWatcherCppSample::MainPage::OnUpdated(Windows::Devices::Enumeration::DeviceWatcher ^sender, Windows::Devices::Enumeration::DeviceInformationUpdate ^args)
{
this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]()
{
tbResult->Text = args->Id + "is Updated";
}));
}
MainPage.xaml:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel VerticalAlignment="Center">
<Button Name="btnClick" Click="btnClick_Click">Click Me to Watch</Button>
<TextBlock Name="tbResult"></TextBlock>
</StackPanel>
</Grid>
这里是完整的演示:DeviceWatcherSample。也可以参考Official Sample的场景二。