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