Keyboard hook get key combination (WPF)

前端 未结 3 473
别那么骄傲
别那么骄傲 2021-01-26 15:16

I tried using this post here: Using global keyboard hook (WH_KEYBOARD_LL) in WPF / C# And i have this sucessfully working.

But there is something i cant get my finger be

3条回答
  •  鱼传尺愫
    2021-01-26 15:46

    To ensure that the key combination is actually pressed by the user, you have to check the state of both key and thus you have to keep track of their state.

    An approach can be :

    List keys = new List();
    
    void KListener_KeyDown(object sender, RawKeyEventArgs args)
    {
       SetKeyDown(args.key);
    
       if(IsKeyDown(Key.LeftCtrl) && IsKeyDown(Key.C))
           MessageBox.Show("Woot!");
    }
    
    void KListener_KeyUp(object sender, RawKeyEventArgs args)
    {
        SetKeyUp(args.key);
    }
    
    private bool IsKeyDown(Key key)
    {
        return keys.Contains(key);
    }
    
    private void SetKeyDown(Key key)
    {
        if(!keys.Contains(key)) 
            keys.Add(key);
    }
    
    private void SetKeyUp(Key key)
    {
        if(keys.Contains(key)) 
            keys.Remove(key);
    }
    

提交回复
热议问题