How to find value of modifier with keypressfcn?

9 次查看(过去 30 天)
Hi, I'm trying to make a simple gui where 'tab' increases variable 'a' and 'shift+tab' decreases it.
Unfortunately, my code can't seem to pick up the shift modifier being pressed?
function varargout = modt(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @modt_OpeningFcn, ...
'gui_OutputFcn', @modt_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
function modt_OpeningFcn(hObject, eventdata, handles, varargin)
handles.a = 0;
guidata(hObject, handles);
function varargout = modt_OutputFcn(hObject, eventdata, handles)
function figure1_KeyPressFcn(hObject, eventdata, handles)
handles = guidata(hObject);
if strcmp(eventdata.Key,'tab')
handles.a = handles.a + 1
elseif strcmp(eventdata.Modifier{:},'shift') && strcmp(eventdata.Key,'tab')
handles.a = handles.a - 1
end
guidata(hObject,handles)
Thanks for the help!

采纳的回答

Geoff Hayes
Geoff Hayes 2015-1-8
Lyn - look closely at your if/elseif
if strcmp(eventdata.Key,'tab')
handles.a = handles.a + 1
elseif strcmp(eventdata.Modifier{:},'shift') && strcmp(eventdata.Key,'tab')
handles.a = handles.a - 1
end
For your elseif there are two conditions:
strcmp(eventdata.Modifier{:},'shift') && strcmp(eventdata.Key,'tab')
So the code will decrement a by one if both conditions are true. BUT, the second condition is the (only) condition for the if statement! So your elseif will never evaluate because the if will always take precedence.
Try the following instead
if strcmp(eventdata.Key,'tab')
if isempty(eventdata.Modifier)
handles.a = handles.a + 1
elseif strcmp(eventdata.Modifier{:},'shift')
handles.a = handles.a - 1
end
end
Try the above and see what happens! Note that you can remove the line
handles = guidata(hObject);
and just use the handles structure that is passed as the third input to this function.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by