问题
I've been using the MouseKeyHook NuGet package for a project where a single key press needs to be monitored to provide explicit functionality. The prototype application I have written, checks the required key is pressed and then sets the Handled property to true. The key I'm testing with is LaunchApplication2, now the problem I'm having is the key press isn't always surpressed, at the moment if Microsoft Word or Excel is in focus then the calculator launches!
The code is as follows:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private IKeyboardMouseEvents keyboardHookListener;
private SolidColorBrush inactiveBrush = new SolidColorBrush(Colors.White);
private SolidColorBrush activeBrush = new SolidColorBrush(Colors.LightGreen);
private bool pressed = false;
public MainWindow()
{
InitializeComponent();
this.Background = inactiveBrush;
this.keyboardHookListener = Hook.GlobalEvents();
this.keyboardHookListener.KeyDown += keyboardHookListener_KeyDown;
this.keyboardHookListener.KeyUp += keyboardHookListener_KeyUp;
}
void keyboardHookListener_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyData == System.Windows.Forms.Keys.LaunchApplication2)
{
if (pressed)
{
this.Background = inactiveBrush;
this.displayLabel.Content = string.Empty;
this.pressed = false;
System.Diagnostics.Debug.WriteLine("*********Finished*********");
}
}
}
void keyboardHookListener_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Filter to specific buttons using the KeyData property of the event arguments.
if (e.KeyData == System.Windows.Forms.Keys.LaunchApplication2)
{
e.Handled = true;
e.SuppressKeyPress = true;
// Use a flag to stop code executing multiple times as whilst a key is pressed the KeyDown keeps firing.
if (!pressed)
{
System.Diagnostics.Debug.WriteLine("*********Started*********");
this.pressed = true;
this.Background = activeBrush;
this.displayLabel.Content = e.KeyData.ToString();
}
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
this.keyboardHookListener.KeyDown -= this.keyboardHookListener_KeyDown;
this.keyboardHookListener.KeyUp -= this.keyboardHookListener_KeyUp;
this.keyboardHookListener.Dispose();
}
}
I've tried using the SuppressKeyPress property as well but that doesn't have any effect. Any explanations or proposals to fix it would be great!
来源:https://stackoverflow.com/questions/31054486/c-sharp-mousekeyhook-key-suppression-problems