私はMediaDevice :: DefaultAudioRenderDeviceChangedとWindows :: Devices :: Enumeration :: DeviceWatcherを処理しようとしました。しかしどちらも期待どおりに働くことができませんでした。
あなたはDeviceWatcher.AddedかDeviceWatcher.Removedイベントを処理するためにDeviceWatcherを使用することができます。
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を:DeviceWatcherSample:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel VerticalAlignment="Center">
<Button Name="btnClick" Click="btnClick_Click">Click Me to Watch</Button>
<TextBlock Name="tbResult"></TextBlock>
</StackPanel>
</Grid>
そして、ここでは完全なデモです。また、Official Sampleのシナリオ2を参照することもできます。
ありがとうエルヴィス。それは携帯電話で動作します!しかし、SpeakerとHeadphoneは "Speakers/Headphones"と呼ばれる同じデバイスを共有しているため、PCではまだ動作しません。 – Lucky
USBヘッドホンが正しく検出されます。 not-USBヘッドホンではできません。それらは 'DeviceClass :: All'でしか検出できず、プラグインイベントだけがアップデートイベントをトリガーします。これはあなたの必要条件に適切な解決策ではありません。だから、私が知る限り、デパートでそれを行う明確な方法はありません。 –