如何在 WPF 应用程序中使用媒体按键和音量变化?

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

我有一个 WPF 应用程序,它应该对我连接到计算机的媒体键和音量旋钮做出反应。

使用 WPF 命令很简单:

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;
}

这行得通(显示了消息框),但问题是系统的其余部分仍然对按钮做出反应 - Spotify play/pauses 按下播放键,系统音量调高或如果转动旋钮,则向下。

我如何使用这些事件,以便只有我的应用程序对它们做出反应,而不是系统的其余部分?

没有可让您定义 system-wide hot keys.

的托管 (.NET) API

您可以尝试使用 Win32 RegisterHotKey API 在您的 WPF 应用程序中注册全局热键:

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

示例请参考以下博客post。

Implementing global hot keys in WPF

您可能还想阅读 this