Figure losing focus on keypress

15 次查看(过去 30 天)
DNF
DNF 2022-11-3
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.

回答(1 个)

Manoj Mirge
Manoj Mirge 2023-2-20
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.

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

产品


版本

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by