Search code examples
matlabpsychtoolbox

Keyboard combination detection in Psychtoolbox-3


I want my experiment to have a key-combination to serve as an indicator to elicit an initiated exit from the experiment.

Now I have this code, which detects a single key press:

while(1)
     [keyIsDown,~,keyCode]=KbCheck;
     if keyIsDown
          if keyCode(SOME_KEY)
                 exitExperiment();
          end
          break;
     end
end

I wish that SOME_KEY would refer to a key combination, like ctrl+r or shift+ESC. Any other solution that will allow to refer to a combination of key presses will surely help.

Thanks.


Solution

  • You can check for a combination of keys, by checking that all of the appropriate key codes in the keyCode logical array are true. Here is an example that requires pressing the left control key and the r key at the same time:

    % setup
    KbName('UnifyKeyNames');
    needed_key_names = {'LeftControl', 'r'};
    needed_key_codes = KbName(needed_key_names);
    
    while(1)
         [keyIsDown,~,keyCode]=KbCheck();
         if keyIsDown
              if all(keyCode(needed_key_codes))
                 break;
              end
         end
    end