The following code works when you press single keys.
@Override public void handleEvent(Event evt) {
switch(evt.type) {
case SWT.KeyDown:
System.out.println(evt.keyCode + " pressed");
break;
case SWT.KeyUp:
System.out.println(evt.keyCode + " released");
break;
}
}
...
widget.addListener(SWT.KeyDown, this);
widget.addListener(SWT.KeyUp, this);
But when you press multiple keys like "A" first then "B", the listener will only receive ke开发者_JAVA百科y up event for "B" and no events for "A". So as a result, ...
switch(evt.type) {
case SWT.KeyDown:
mKeyMap.get(evt.keyCode).isDown = true;
break;
case SWT.KeyUp:
mKeyMap.get(evt.keyCode).isDown = false;
break;
}
The key "A" will always remain true, until you press it again and receive key down event and key up event. This problem doesn't happen with the arrow keys though. You can press multiple arrow keys and it sends key up events correctly.
So, why isn't key released event sent for key "A" when keys "A" and "B" are pressed?
Looking around (as I have the same problem for a spot of game code) I found this Eclipse bug:
Bug 50020 - KeyReleased not working correctly.
Seems like the problem has been around for some 8 years and is not likely to be solved / patched anytime soon. :(
This can be influenced by your keyboard to an extent. I'm not sure if that's what might be causing your problem, though, but take a look at this link:
http://www.tomshardware.com/forum/50383-28-pressing-multiple-keys-keyboard-problem
function isUserPressingCopy(){
var copy = ["Meta", "c"]
var map = {};
let buttonPressed = []
onkeydown = onkeyup = function(event){
event;
map[event.key] = event.type == 'keydown';
buttonPressed.push(map[event.key])
if (Object.values(map).every(item => item === true)){
if(JSON.stringify(Object.keys(map)) == JSON.stringify(copy))
console.log("you pressed copy")
}
else{
map = {}
}
}
}
When you declare this function in your console and execute it, you should be able to do "cmd" + "c" on mac and the console will tell you if you pressed copy (by comparing it to the copy variable I set).
This is my way of checking two keys were pressed pressed, I had to create an object storing the keys pressed, create an object for the expected keys and stringify them in array form for comparison, personally this is my preferred way of searching for multiple keypress events.
(tried to simplify this by using a hotkey as an example but I hope it helps!)
精彩评论