Tengo una aplicación WPF que se supone que reacciona a las teclas multimedia y una perilla de volumen que he conectado a la computadora.
Esto fue sencillo usando los comandos de WPF:
Ventana principal.xaml:
<CommandBinding Command="local:Commands.VolUp" CanExecute="VolUpCommand_CanExecute" Executed="VolUpCommand_Executed" /> <CommandBinding Command="local:Commands.Play" CanExecute="PlayCommand_CanExecute" Executed="PlayCommand_Executed" />Comandos.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) } );Ventana principal.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; }Esto funciona (se muestran los cuadros de mensaje), pero el problema es que el resto del sistema aún reacciona a los botones: Spotify reproduce/pausa al presionar reproducir, y el volumen del sistema cambia hacia arriba o hacia abajo si se gira la perilla.
¿Cómo consumo estos eventos de modo que solo mi aplicación reaccione ante ellos, pero no el resto del sistema?
No existe una API administrada (.NET) que le permita definir teclas de acceso rápido para todo el sistema .
Puede intentar usar la API de Win32 RegisterHotKey para registrar una tecla de acceso rápido global en su aplicación WPF:
[DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);Consulte la siguiente entrada de blog para ver un ejemplo.
Implementación de teclas de acceso rápido globales en WPF
Es posible que también desee leer esto .