Multiple KeyPressFcn functions?
14 views (last 30 days)
Show older comments
Is it somehow possible to have multiple functions that get called in a figure's KeyPressFcn?
Suppose I have a function for a figure that assigns it a KeyPressFcn that performs an action when I hit the 'a' key. Now suppose I have a second function for a figure that assigns it a KeyPressFcn that performs an action when I hit the 'b' key. Ideally, I could run both functions and be able to get a response from both the 'a' and 'b' keys.
In actuality, when I run both of those functions, the last one to run overwrites the figure.KeyPressFcn property. Is there a way to get both functions to get assigned to the figure's KeyPressFcn? I tried using a cell array.
I know I could just combine both functions into one (which would also ensure there aren't keypress conflicts), but it would be nice if I could keep separate actions in separate functions (so I can mix and match depending on application).
0 Comments
Accepted Answer
Walter Roberson
on 8 Feb 2018
Set the actual keypressfcn to a routine that you write, a key press dispatcher. The dispatcher would retrieve a cell array of function handles and invoke them one by one. In the places in the code that would set the keypressfcn, instead have them call a "register" function that adds the given function handle to the list of known callbacks.
Alternately, you might be be able to do this by invoking listeners on an event. You can have as many listeners on the same event as you want, with MATLAB internally doing the registration and invocation.
For example,
el = addlistener(fig, 'CurrentKey', 'PostSet', @(varargin) disp('keyed!'))
but not this exactly: the above does not "eat" the key presses, and they end up being forwarded to the command line. But you can then
set(fig,'KeyPressFcn', @(varargin) disp('eating key'))
and this will eat the keypress . (In practice you would just have it do nothing, gracefully, such as @(varargin) 0 )
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!