tomzx / gkm

⚠ Unsupported/Unmaintained ⚠️️ Global Keyboard and Mouse listener for node.js.
MIT License
52 stars 16 forks source link

How to prevent keyboard long pressed? #16

Closed oukunan closed 6 years ago

oukunan commented 6 years ago

Is it possible to prevent that?

tomzx commented 6 years ago

Could you explain your use case in more details?

Normally if you subscribe to key.pressed and key.released, you will receive only 1 event when the key is pressed and one once it's released, such that a "long" or "short" key press/release are handled the same way.

oukunan commented 6 years ago

@tomzx I'm try to count keystroke. gkm work fine but when I try long keypressed the number of couter increment so fast. let counter = 0; gkm.event.on('key.pressed',() => { ++counter console.log(counter) }) I suppose when I long keypressed the counter. It's should increment counter only 1 not continue increment.

tomzx commented 6 years ago

You probably want to trigger the first time key.pressed is called, have a small object which contains which keys are currently pressed (something like {'a': true, 'c': true}, and on key.released remove the key from the list. This way, you check if the key is currently in this object, and if it is, then you ignore the key press.

This way you can trigger an event on the initial key.pressed, ignore subsequent events, then do something else on key.released (if necessary).


const pressedKeys = {};

gkm.events.on('key.pressed', function(data) {
    if (pressedKeys[data]) {
        // Ignore
        return;
    }

    pressedKeys[data] = true;

    console.log(this.event + ' ' + data);
});

gkm.events.on('key.released', function(data) {
    delete pressedKeys[data];

    console.log(this.event + ' ' + data);
});
``` 
oukunan commented 6 years ago

@tomzx That's work. Thanks!