Home > front end >  How to consume media key presses and volume changes in a WPF Application?
How to consume media key presses and volume changes in a WPF Application?

Time:03-17

I have a WPF application that is supposed to react to media keys and a volume knob I have connected to the computer.

This was straightforward using WPF commands:

MainWindow.xaml:

<CommandBinding Command="local:Commands.VolUp" CanExecute="VolUpCommand_CanExecute" Executed="VolUpCommand_Executed" />
<CommandBinding Command="local:Commands.Play" CanExecute="PlayCommand_CanExecute" Executed="PlayCommand_Executed" />

Commands.cs:

public static readonly RoutedUICommand VolUp = new RoutedUICommand
(
  "VolUp",
  "VolUp",
  typeof(Commands),
  new InputGestureCollection()
  {
    new KeyGesture(Key.VolumeUp)
  }
);
public static readonly RoutedUICommand Play = new RoutedUICommand
(
  "Play",
  "Play",
  typeof(Commands),
  new InputGestureCollection()
  {
    new KeyGesture(Key.MediaPlayPause)
  }
);

MainWindow.xaml.cs:

private void VolUpCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
  e.CanExecute = true;
}
private void VolUpCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
  MessageBox.Show("Volume up");
  e.Handled = true;
}
private void PlayCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
  e.CanExecute = true;
}
private void PlayCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
  MessageBox.Show("Play");
  e.Handled = true;
}

This works (the message boxes are shown), but the problem is that the rest of the system still reacts to the buttons - Spotify play/pauses on the play press, and the system volume is changed up or down if the knob is turned.

How do I consume these events such that only my application reacts to them, but not the rest of the system?

CodePudding user response:

There is no managed (.NET) API that lets you define system-wide hot keys.

You could try to use the Win32 RegisterHotKey API to register a global hot key in your WPF application:

[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

Please refer to the following blog post for an example.

Implementing global hot keys in WPF

You may also want to read this.

  • Related