Educational materials

Keystroke Retrieval in Matlab

Reference Link @ MATLAB primary website

Using the KeyPressFcn

This example, creates a figure and defines a function handle callback for 
the KeyPressFcn property.  When the "e" key is pressed, the callback 
exports the figure as an EPS file. When Ctrl-t is pressed, the callback 
exports the figure as a TIFF file.

function figure_keypress
   figure('KeyPressFcn',@printfig);

   function printfig(src,evnt)
      if evnt.Character == 'e'
         print ('-deps',['-f' num2str(src)])
      elseif length(evnt.Modifier) == 1 & strcmp(evnt.Modifier{:},'control') & evnt.Key == 't'
         print ('-dtiff','-r200',['-f' num2str(src)])
   end
end

Other Relevant Background Notes

  • gcf gives the handle of the current figure

Modified Key Retrieval

The code is fairly simple:

  • Access the Current Character property of the global figure handle
  • If it is empty, there is not a key pressed
  • Otherwise, simply compare versus the current keypress
  • An additional catch for the various arrow keys is added to allow calling the function with strings of upArrow, downArrow, leftArrow, and rightArrow for comparison. While one can simply use the ASCII value itself, this will slightly simplify function calls.

function [keyPressed]= isKeyPressed(keyToCheck)

   currentKey = get(gcf, 'CurrentCharacter');

% Is there anything to process?
   if isEmpty(currentKey) == 1
      keyPressed = 0; 
      return;
   end

% Default is 0 unless we find otherwise
   keyPressed = 0;

% Quick check of an exact match
   if keyToCheck == currentKey
      currentKey= 1;
   else 
% Exceptions using string checks for the string mappings of arrows
%   (our mapping, not MATLAB's)
      if strcmp(keyToCheck, 'upArrow') == 1;
         if currentKey == 24
            keyPressed = 1
         end
      end  
      if strcmp(keyToCheck, 'downArrow') == 1;
         if currentKey == 25
            keyPressed = 1
         end
      end  
      if strcmp(keyToCheck, 'rightArrow') == 1;
         if currentKey == 26
            keyPressed = 1
         end
      end  
      if strcmp(keyToCheck, 'leftArrow') == 1;
         if currentKey == 27
            keyPressed = 1
         end
      end  
   end
end
  Attachment Action Size Date Who Comment
else convertArrowKeyCounts.m props, move 1.9 K 11 Jul 2007 - 02:17 AaronStriegel 2006 Variant - convertArrowKeyCounts
r1 - 11 Jul 2007 - 02:53:15 - AaronStriegel
This site is powered by the TWiki collaboration platformCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback
Syndicate this site RSSATOM