Dante1986
Dante1986

Reputation: 59939

Keyboard hook get key combination (WPF)

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 behind. It can detect every single key pressed, but i like to make my app do something on a key combination.

void KListener_KeyDown(object sender, RawKeyEventArgs args)
        {
            Console.WriteLine(args.Key.ToString());
            if (args.Key == Key.LeftCtrl && args.Key == Key.C)
            {
                MessageBox.Show(args.Key.ToString());
            }
        }

Obvious, this does not work, as the void only is for every single key (if i understand correct)

So i really need some help to get it working for a key combination, for example Ctrl + C could someone push me in the right direction here ?

Upvotes: 0

Views: 5299

Answers (3)

dna
dna

Reputation: 1075

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<Key> keys = new List<Key>();

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

Upvotes: 1

user2480047
user2480047

Reputation:

Some time ago I relied on the RegisterHotKey function and the result was pretty good. I used this in VB.NET and just for combinations of CTRL/SHIFT/ALT + letter or number, but here you have a pretty detailed C# code allowing even more combinations.

Upvotes: 0

Romano Zumb&#233;
Romano Zumb&#233;

Reputation: 8079

Store the value of the key that is pressed and the next time your method is called check if this stored value and the actual value are your key combination.

    var lastKey;
void KListener_KeyDown(object sender, RawKeyEventArgs args)
        {

            Console.WriteLine(args.Key.ToString());
            if (lastKey == Key.LeftCtrl && args.Key == Key.C)
            {
                MessageBox.Show(args.Key.ToString());
            }
           lastKey = args.Key;
        }

Upvotes: 6

Related Questions