我有一個 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" />
命令.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 播放/在播放按下時暫停,并且如果轉動旋鈕,系統音量會向上或向下改變。
我如何使用這些事件,以便只有我的應用程式對它們做出反應,而不是系統的其余部分?
uj5u.com熱心網友回復:
沒有可讓您定義系統范圍熱鍵的托管 (.NET) API 。
您可以嘗試使用 Win32 RegisterHotKeyAPI 在 WPF 應用程式中注冊全域熱鍵:
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
有關示例,請參閱以下博客文章。
在 WPF 中實作全域熱鍵
您可能還想閱讀這篇文章。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/445014.html
上一篇:使用集合屬性展平物件
