Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab: difference between KeyPressFcn and WindowKeyPressFcn

The Matlab documentation definition for KeyPressFcn is a "callback function invoked by a key press that occurs while the figure window has focus."

Similarly, the definition for WindowKeyPressFcn is a "callback function invoked by a key press that occurs while either the figure window or any of its children has focus."

As far as I understand, the children of figures are entities like axes, plot objects, and annotation objects. If one of these children has focus, then its parent figure presumably also has focus (at least its handle would be returned by gcf). Therefore, I don't see any practical distinction between KeyPressFcn and WindowKeyPressFcn other than that the former, by implication of its name lacking the term Window, might also take effect when no figures are active, such as when operating in the command window (though this conjecture is in disagreement with the callbacks definition, which explicitly invokes the presence of a figure window).

Could someone pleas explain the difference between these two callback functions and when use of one over the other might be preferred?

like image 509
user001 Avatar asked Aug 07 '14 04:08

user001


1 Answers

As you suggest in your question the difference is in focus.

  • KeyPressFcn is evaluated only when the figure has focus (but not its children).
  • WindowKeyPressFcn, on the other hand, is evaluated whenever the figure or any of its children has focus.

This can be illustrated with following code:

function test_keypress_vs_windowkeypress

h.hf = figure();
h.edit = uicontrol('Style', 'edit', 'Units', 'Normalized',...
    'Position', [0.2, 0.2, 0.6, 0.6]);

% set callbacks
set(h.hf, 'KeyPressFcn', @wintest);
set(h.edit, 'KeyPressFcn', @edittest);

function wintest(h, e)
    disp('window button press');

function edittest(h, e)
    disp('editbox button press');

The function creates a figure (that has a KeyPressFcn) with an ugly edit box (has a KeyPressFcn too).
Now if you:

  • press any key when the edit box has focus only the edittest callback is evaluated.
  • press any key when the figure has focus only the wintest callback is evaluated.
  • change the window callback to be WindowKeyPressFcn and press a key while the edit box has focus - both callbacks will be evaluated (first the figure callback then the edit box callback).
like image 200
mmagnuski Avatar answered Sep 21 '22 11:09

mmagnuski