Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to consume media key presses and volume changes in a WPF Application?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading