GUIDE: Calling button press on key press

조회 수: 3 (최근 30일)
Philip
Philip 2011년 3월 1일
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?
Thanks!

채택된 답변

Oleg Komarov
Oleg Komarov 2011년 3월 1일
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],...
'menubar','none',...
'name','gui',...
'numbertitle','off',...
'resize','off',...
'WindowKeyPressFcn',@pb_kpf);
S.pb = uicontrol('style','push',...
'units','pix',...
'position',[10 10 180 40],...
'fontsize',14,...
'string','Hi!',...
'call',@pb_call);
S.tx = uicontrol('style','text',...
'units','pix',...
'position',[10 55 180 40],...
'string','goodbye',...
'fontsize',23);
% Callback for pushbutton, prints Hi! in cmd window
function pb_call(varargin)
set(S.tx,'String', get(S.pb,'String'))
end
% Do same action as button when pressed leftarrow
function pb_kpf(varargin)
if if strcmp(varargin{1,2}.Key, 'leftarrow')
pb_call(varargin{:})
end
end
end
You may also want to give a look at a very similar question: gui for keyboard pressed representing the push button
Oleg
  댓글 수: 2
Jiro Doke
Jiro Doke 2011년 3월 1일
In the last function "pb_kpf", if you examine varargin{1,2}.Key instead of varargin{1,2}.Character, you'll be able to capture "rightarrow" and "leftarrow".
In that case, be sure to use "strcmp" for the comparison:
if strcmp(varargin{1,2}.Key, 'leftarrow')
...
end
Philip
Philip 2011년 3월 1일
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!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by