GUIDE: Calling button press on key press

15 views (last 30 days)
Philip on 1 Mar 2011
Does anyone know of a way to enable the callback for a button press (as if it were clicked) when a user presses a specified key on the keyboard?
For example, if the user presses the left cursor, it will enable button A, but if they press the right cursor, it will enable button B?

Accepted Answer

Oleg Komarov
Oleg Komarov on 1 Mar 2011
An example with WindowKeyPressFcn set at the figure level. Whenever you push 'p' te action is the same pushing the button:
EDIT (Per Jiro's suggestion in the comments)
function [] = gui()
S.fh = figure('units','pixels',...
'position',[500 200 200 100],...
S.pb = uicontrol('style','push',...
'position',[10 10 180 40],...
S.tx = uicontrol('style','text',...
'position',[10 55 180 40],...
% Callback for pushbutton, prints Hi! in cmd window
function pb_call(varargin)
set(S.tx,'String', get(S.pb,'String'))
% Do same action as button when pressed leftarrow
function pb_kpf(varargin)
if if strcmp(varargin{1,2}.Key, 'leftarrow')
You may also want to give a look at a very similar question: gui for keyboard pressed representing the push button
Philip on 1 Mar 2011
Thank you both for your help. I have used 'eventdata.Key' on the figure WindowKeyPressFcn and used case statements to capture the activity and call the relevant functions.
Thanks again!!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by