- A listener cannot prevent other listeners from being notified that the event occurred.
- The order in which listeners execute is not defined.
Figure losing focus on keypress
조회 수: 9 (최근 30일)
이전 댓글 표시
I write a lot of code for doing mouse and keyboard interaction with graphics objects. I often have multiple different functions listening for keypresses or mouse movements, and for that reason it is impractical to use callbacks for WindowButtonDownFcn etc, since they will clobber eachother, and instead I use listeners for events, like WindowMousePress etc:
lst = listener(hfig, "WindowKeyPress", @mycallback)
Unfortunately, this does not work well, since my figure loses focus the moment I press a key. The only way to keep the figure in focus is by populating the hfig.WindowKeyPressFcn field with some dummy function, like hfig.WindowKeyPressFcn = @(~,~)0.
This is annoying and seems brittle. How can I keep the figure in focus without fiddling with the WindowKeyPressFcn field?
I am not eager to issue commands like figure(hfig) to regain focus, since my callbacks are often just inline anonymous functions.
댓글 수: 0
답변 (1개)
Manoj Mirge
2023년 2월 20일
Hi DNF,
As per my knowledge, there are certain limitations to the use of events:
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!