Hi DNF,
As per my knowledge, there are certain limitations to the use of events:
- A listener cannot prevent other listeners from being notified that the event occurred.
- The order in which listeners execute is not defined.
So, there exists a default listener for every graphical object's event. In case of figure's WindowKeyPress event the default callback makes figure lose its focus on any key press. As stated in the above limitations the listeners defined by users cannot prevent default listener from executing , that is why irrespective of number of listeners you create the default listener will make figure loose its focus on key press. The default behaviour can only be changed by changing WindowKeyPressFcn property of figure object , as this will overwrite the default listener’s callback handle .
So Instead of giving empty anonymous function handle to WindowKeyPressFcn property you can create function named preventDefault that sets empty anonymous function handle to your property. This will make your code more readable.
f=figure;
%add listeners
preventDefault(f,'WindowKeyPressFcn');% This will set empty anonymous function handle to object's property.
%The function that will set empty anonymous function handle to property of object.
function preventDefault(obj,property)
set(obj,property,@(~,~)0);
end
You can read more about the same using following resources:
I hope this will help.