Search code examples
c#windowsuwpuwp-xaml

How can I detect click on music buttons?


I have in my app buttons like this. Buttons

I'd like to know how to detect click on it


Solution

  • The buttons in the image you posted come from the SystemMediaTransportControls Class. It seems that you are playing media from your app. If you want to detect the button click event in the image that you posted. You will have to get the current SystemMediaTransportControls object in your app and handle its ButtonPressed Event.

    Like this:

            mediaPlayer = new MediaPlayer();
            mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/video.mp4"));
            mediaPlayer.Play();
    
            _systemMediaTransportControls = mediaPlayer.SystemMediaTransportControls;
            _systemMediaTransportControls.IsPlayEnabled = true;
            _systemMediaTransportControls.IsPauseEnabled = true;
            _systemMediaTransportControls.ButtonPressed += _systemMediaTransportControls_ButtonPressed;
    
    
     private async void _systemMediaTransportControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
        {
            switch (args.Button)
            {
                case SystemMediaTransportControlsButton.Play:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        MyTextBlock.Text = "Play";
                        mediaPlayer.Play();
                    });
                    break;
                case SystemMediaTransportControlsButton.Pause:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        MyTextBlock.Text = "Pause";
                        mediaPlayer.Pause();
                    });
                    break;
                case SystemMediaTransportControlsButton.Next:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        MyTextBlock.Text = "Next";
                    });
                    break;
                case SystemMediaTransportControlsButton.Previous:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        MyTextBlock.Text = "Previous";
                    });
                    break;
                default:
                    break;
            }
        }
    

    If you are using MediaElement to play media, you need use another way to get the SystemMediaTransportControls like this:

    _systemMediaTransportControls = SystemMediaTransportControls.GetForCurrentView();
    

    For more information, please check: Manual control of the System Media Transport Controls