C#MouseKeyHook键抑制问题

时间:2015-06-25 15:22:48

标签: c# mousekeyhook

我一直在使用MouseKeyHook NuGet包进行一个项目,在这个项目中需要监视单个按键以提供显式功能。我编写的原型应用程序,检查按下所需的键,然后将Handled属性设置为true。我正在测试的关键是LaunchApplication2,现在我遇到的问题是按键并不总是被压抑,此时如果Microsoft Word或Excel处于关注状态,那么计算器就会启动!

代码如下:

    /// <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();
    }
}

我也尝试过使用SuppressKeyPress属性,但这没有任何效果。任何解释或提议来解决它都会很棒!

0 个答案:

没有答案