Adding event handlers: Sounds, Dark Mode & Windowing (Part 2)

Adding event handlers: Sounds, Dark Mode & Windowing (Part 2)


Note that in part 1 of the WinAppSDK Blog Series you implemented the visual layer of the DrumPad using WinUI 3 controls. However, if you click on any buttons, nothing happens, because we have not defined any actions, which we will do now. You will be guided to accomplish the following in this post: 

  • Play a sound when a drum pad button is clicked
  • Switch into dark mode when the toggle switch is turned on
  • Go into a specific windowing mode when a presenter mode is selected

Play a sound when a drum pad button is clicked

  1. Download sound clips to your project’s Assets folder

NOTE: You may download any .wav sound clips for this part. Optionally, you could use my sound clips here as well. Store the sound clips under your project’s Assets folder because that is the folder path we will provide to specify which sound to play.

    2. Install the System.Windows.Extensions NuGet Package

NOTE: Playing a sound in WinUI apps requires using a library called System.Media, accessible through a NuGet Package. Following these two steps to install the NuGet Package in Visual Studio:

  • Navigate to Solution Explorer, under Dependencies, right-click on Packages, select Manage NuGet Packages
  • Select the Browse tab, search System.Windows.Extensions and install it

    3. Add the following namespace to MainAppWindow.xaml.cs:

using System.Media;

4. Create a call-back function that plays a sound in class MainWindow : Window :

MainAppWindow.xaml.cs:

private void pad_clicked(object sender, RoutedEventArgs e)
{
    // get the full path to your app’s folder where it is installed
    var installedPath = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
    // join path above with the sub-paths in your Assets folder and the specific sound file
    var soundFile = Path.Join(installedPath, "Assets", "rim.wav");

    SoundPlayer player = new System.Media.SoundPlayer(soundFile);
    player.Play();
}

5. link the call-back function above to a button via the Click parameter:

MainWindow.xaml:



Source link

Leave a Reply

Your email address will not be published.