matlab: difference between KeyPressFcn and WindowKeyPressFcn

♀尐吖头ヾ 提交于 2019-12-14 03:46:04

问题


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?


回答1:


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).


来源:https://stackoverflow.com/questions/25174400/matlab-difference-between-keypressfcn-and-windowkeypressfcn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!