1

我一直在将 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 属性,但这没有任何效果。任何解决它的解释或建议都会很棒!

4

0 回答 0